[英]ggplot is not correctly grouping bars when using position="dodge"
快疯了。 我有一个融化的 dataframe,我试图在 ggplot2 的简单分组条形图中显示:
modality <- c("CLASS", "CLASS", "ONLINE", "ONLINE", "HYBRID", "HYBRID")
survey <- c("A Pre", "A Post", "B Pre", "B Post", "C Pre", "C Post")
score <- c(3.45, 4.15, 4.12, 4.34, 4.06, 4.57)
df = data.frame(modality, survey, score)
ggplot(df, aes(fill=modality, y=score, x=survey)) +
geom_bar(position="dodge", stat="identity")
我尝试将其设置为尽可能接近r-graph-gallery 中的示例,它工作得很好。
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar(position="dodge", stat="identity")
我看不出这两个数据帧的结构有什么不同,但我认为存在一个。 我真的很想知道我在这里缺少什么。 谢谢!
每个值在 pre、post 即 'A pre'、'B pre' 等中是不同的,类似地,'A post'、'B post' 等。如果我们通过删除前缀部分使其成为一个公共组,留下 ' pre/post' 那么它将给出类似的 output ,如示例所示
library(dplyr)
library(stringr)
library(ggplot2)
df %>%
mutate(survey = str_remove(survey, '\\D+\\s+')) %>%
ggplot(aes(fill = modality, y = score, x = survey)) +
geom_bar(position = "dodge", stat = "identity")
-输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.