【问题标题】:geom_bar with x and fill aesthetics by one factor and dodge by a second带有 x 的 geom_bar 并以一个因子填充美学并以一秒闪避
【发布时间】: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))

我想使用ggplot2geom_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()

或者相反 - ageaes(x) 参数和 idfill 参数:

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多