代码之家  ›  专栏  ›  技术社区  ›  dan

创建一个按相同因子着色和x定位的分组几何图形条

  •  1
  • dan  · 技术社区  · 5 年前

    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 这样,杆件首先被分开( dodge d) 借 age id (沿x轴,带间隙),并由 身份证件 .

    我只熟悉设置 aes(x) 论据 身份证件 fill :

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

    enter image description here

    或者相反的情况,即 论据 年龄 论据 身份证件 :

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

    enter image description here

    填满 身份证件 而不是 年龄 .

    position 和/或 stat 价值观得到了这一点。有什么想法吗?

    0 回复  |  直到 5 年前
        1
  •  0
  •   Henrik plannapus    5 年前

    你可以使用 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