【发布时间】: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,我现在明白了。带来不便敬请谅解。即使问题已经解决,我现在也应该添加它吗?