我有一个数据框:
df <- data.frame(human = c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
stage = c("A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4"),
class = c(0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0)
)
并且想要在x轴上每个阶段的条形图:
ggplot(df, aes(x = stage, y = class, fill = as.factor(human))) + geom_bar(stat = "identity") + scale_y_continuous(limits = c(0,15))
看起来不错,但我希望人类元素并排放置,所以我添加了position = "dodge"
:
ggplot(df, aes(x = stage, y = class, fill = as.factor(human))) + geom_bar(stat = "identity", position= "dodge") + scale_y_continuous(limits = c(0,15))
因为使用stat = "identity"
。因此,您必须先算数。
library(tidyverse)
df %>%
count(stage, class, human) %>%
ggplot(aes(x = stage, y = n, fill = as.factor(human))) +
geom_bar(stat = "identity", position = "dodge")
ggplot2移至躲避样式时未正确执行求和。与找出预期的行为相反,一个简单的解决方案是使用“ dpylr's” summarize
函数执行求和,然后绘制结果:
library(dplyr)
df2<-df %>% group_by(human=as.factor(human), stage) %>% summarize(class=sum(class))
ggplot(df2, aes(x = stage, y = class, fill = as.factor(human))) +
geom_bar(stat = "identity", position= "dodge") +
scale_y_continuous(limits = c(0,15))
避免使用dplyr
进行预处理的解决方案:
stat_summary