【问题标题】:Creating Grouped Bar-plots for Multiple Cluster Columns in R在 R 中为多个簇列创建分组条形图
【发布时间】:2019-07-15 17:49:01
【问题描述】:

期望的行为:我想为我的数据集的多列创建一个分组条形图,针对具有低、中和高值的分类变量绘制分组条形图。例如,对于下面显示的数据集,我想为 x 轴上的每个“B”、“M”、“LA”等创建一个三组条形图,同时填充每个三个的条形-根据类别按其值的平均值分组。

我已尝试使用以下代码来解决此问题,但我似乎无法理解我在这里做错了什么,因为代码会引发错误,即这些值不会按维度相加。谁能让我知道这里有什么问题,据我所知,ggplot 的所有填充方面似乎都符合我的要求? ...

df <- data.frame(B=c(1,2,4,-5,8,9,8,4,5),GM=c(5,5,4,-7,9,8,7,-4,6),
             LA=c(-5,8,5,-8,4,5,6,1,7), NS= c(-5,-8,-5,-8,4,5,-6,1,7), 
SL=c(-5,8,5,-8,-4,-5,6,-1,-7), data.SWASH_group=c("low", "medium", "low", 
"high", "high", "low", "medium", "low", "high"))

species=c(df$B, df$GM, df$LA, df$NS, df$SL)

condition=c(df$data.SWASH_group=="low", df$data.SWASH_group=="medium", 
df$data.SWASH_group=="high")

value=c(mean(df$B), mean(df$GM), mean(df$LA), mean(df$NS), mean(df$SL))

# For Grouping
library(ggplot2)

ggplot(df, aes(fill=condition, y=value, x=species)) + 
geom_bar(position="dodge", stat="identity")

This is how the head of my real dataset - df - looks like (The one in the 
code is just for example purposes):

B           GM          LA          NS          SL          data.SWASH_group
561.5806    533.5484    602.4000    675.4706    621.5758    low
780.5758    615.8788    801.8788    589.2903    875.0938    medium
649.9697    658.9091    789.1818    638.4412    646.5455    medium

... 我希望输出看起来像这样:

这是我自己的代码产生的输出:

【问题讨论】:

  • 嗨,您需要为 Stack Overflow 提出更多问题reproducible,干杯。
  • @jay.sf 嗨,现在好些了吗?我是新手,因此我在这里没有太多经验。
  • 不幸的是,没有:-( 可重现的意思是:当我运行你的代码时,我没有得到Error: object 'df' not found。你还需要提供一些示例数据。最好使用dput
  • 也就是说,您的向量长度不同。 condition 的长度为 3 * nrow(df)value 的长度为 5,物种的长度为 5 * nrow(df)。这不能顺利!
  • @January,我现在明白了。带来不便敬请谅解。即使问题已经解决,我现在也应该添加它吗?

标签: r grouping bar-chart


【解决方案1】:

我们需要可重复的数据来解决您的问题。 但是,如果我正确理解了您的描述,这应该可以:

library(ggplot2)
library(dplyr)
library(reshape2)

df <- data.frame(A=c(1,2,4,5,8,9,8,4,5),B=c(5,5,4,7,9,8,7,4,6),
                 C=c(5,8,5,8,4,5,6,1,7), 
                 group.var=c("low", "medium", "low", "high", "high", "low", "medium", "low", "high"))

df.agg <- df %>% group_by(group.var) %>% summarise_all(funs(mean))
df.agg <- melt(df.agg)

ggplot(df.agg) + 
  geom_bar(aes(x=variable, y = value, fill = as.factor(group.var)),
           position="dodge", stat="identity")

【讨论】:

  • 我尝试了左右连接。而不是在此之前分组。这完美地工作,除了负值由于某种原因没有绘制在 y 轴刻度上?数据集确实有负值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多