【发布时间】:2021-10-04 14:05:27
【问题描述】:
我有这个data.frame:
df <- data.frame(id = c("A","A","B","B","C","C"),
age = rep(c("young", "old"), 3),
value = c(20,15,7,5,2,6))
我想使用ggplot2 的geom_bar 绘制它,这样条形首先由age 分隔(dodged)(但它们之间没有间隙),然后由@987654331 分隔@(沿 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()
或者相反 - age 的 aes(x) 参数和 id 的 fill 参数:
ggplot(df, aes(x = age, y = value)) +
geom_bar(aes(fill = id), position = "dodge", stat = "identity") +
theme_minimal()
但我想要的情节看起来像上面的第一个情节,但只有filled 由id 而不是age。
可能有一个组合 position 和/或 statvalues 可以做到这一点。有什么想法吗?
【问题讨论】:
-
嗨@dan!我冒昧地将“组”变量重命名为“id”,以避免与答案中使用的
group参数混淆。干杯
标签: r ggplot2 position geom-bar stat