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

问题描述 投票:0回答:4

我有一个数据框:

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))

enter image description here

看起来不错,但我希望人类元素并排放置,所以我添加了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))

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

r ggplot2 geom-bar
4个回答
1
投票

这是因为您的“标识”为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


0
投票

因为使用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")

0
投票

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))

enter image description here


0
投票

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

stat_summary
© www.soinside.com 2019 - 2024. All rights reserved.