期望的行为:我想创建一个多列的数据集的分组条形图,针对值分别为low,medium和high的分类变量绘制分组的条形图。例如,对于下面显示的数据集,我想在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
... 我希望输出看起来像这样:
这是我自己的代码产生的输出:
答案 0 :(得分:0)
我们需要可复制的数据来解决您的问题。 但是,如果我正确理解了您的描述,这应该可以起作用:
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")