geom_bar 与 x 和填充美学由一个因素和闪避一秒

问题描述

我有这个data.frame

df <- data.frame(id = c("A","A","B","C","C"),age = rep(c("young","old"),3),value = c(20,15,7,5,2,6))

我想使用 ggplot2geom_bar 来绘制它,这样条形首先由 dodge 分隔 (aged)(但之间没有间隙它们),然后由 id(沿 x 轴,有间隙)分隔,并由 id 着色。

我只熟悉将 aes(x) 参数设置为 id 并将 fill 参数设置为 age

ggplot(df,aes(x = id,y = value)) + 
 geom_bar(aes(fill = age),position = "dodge",stat = "identity") +
 theme_minimal()

enter image description here

或者相反 - aes(x)age 参数和 fillid 参数:

ggplot(df,aes(x = age,y = value)) + 
 geom_bar(aes(fill = id),stat = "identity") +
 theme_minimal()

enter image description here

但我想要的是情节看起来像上面的第一个情节,但只有 fillid 而不是 age

可能有 position 和/或 stat 值的组合可以获得这一点。有什么想法吗?

解决方法

您可以在 group 中使用 aes 参数:

ggplot(df,aes(x = id,y = value)) +
  geom_bar(aes(group = age,fill = id),position = "dodge",stat = "identity") +
  theme_minimal()

enter image description here