为什么在我的`geom_bar`中添加`position =“ dodge”`导致值显示不正确?

我有一个数据框:

df <- data.frame(human = c(1,2,3,4,5,1,5),stage = c("A1","A2","A3","A4","A1","A4"),class = c(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))

为什么在我的`geom_bar`中添加`position =“ dodge”`导致值显示不正确?

看起来不错,但我希望人为因素并列,因此我添加了position = "dodge"

ggplot(df,fill = as.factor(human))) + geom_bar(stat = "identity",position= "dodge") + scale_y_continuous(limits = c(0,15))

虽然各列现在并排,但由于某种原因,所有班级= 1:

为什么在我的`geom_bar`中添加`position =“ dodge”`导致值显示不正确?

l464547980 回答:为什么在我的`geom_bar`中添加`position =“ dodge”`导致值显示不正确?

这是因为您的“身份”是0或1。一种解决方法是在绘制数据之前summarize。例如:

library(tidyverse)

df %>% 
    group_by(human,stage) %>% 
    summarise(class = sum(class)) %>% 
    ggplot(aes(x = stage,y = class,fill = as.factor(human))) + 
    geom_bar(stat = "identity",position= "dodge")

enter image description here

,

避免使用dplyr进行stat_summary预处理的解决方案:

ggplot(df,aes(x = stage,fill = as.factor(human))) + 
  stat_summary(geom = "bar",position = "dodge",fun.y = "sum")
,

因为您使用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")
本文链接:https://www.f2er.com/3164963.html

大家都在问