【问题标题】:Group variables in ggplot2 (geom_col)ggplot2 (geom_col) 中的组变量
【发布时间】:2020-12-12 12:05:12
【问题描述】:

我想将数据框中的变量绘制到不同的组中,但不知道如何做到这一点。

模拟数据框:

df<-data.frame(animal=c("cat1","cat2","mouse1","mouse2","dog1","dog2"),size=c(3,4,1,2,6,7))
plot<-ggplot(df)+geom_col(mapping=aes(x=animal,y=size))
plot 

我想要的输出应该是这样的:

【问题讨论】:

    标签: r dataframe ggplot2


    【解决方案1】:

    我会建议下一个方法。您必须创建一个组,然后使用构面。我从@AllanCameron 学到的大部分技巧对于这种风格的问题都有很好的答案。接下来是可以做到这一点的代码:

    library(tidyverse)
    #Data
    df<-data.frame(animal=c("cat1","cat2","mouse1","mouse2","dog1","dog2"),
                   size=c(3,4,1,2,6,7),stringsAsFactors = F)
    #Create group
    df$Group <- gsub('\\d+','',df$animal)
    #Now plot
    ggplot(df,aes(x=animal,y=size))+
      geom_col()+
      facet_wrap(.~Group,scales = 'free', strip.position = "bottom")+
      theme(strip.placement  = "outside",
            panel.spacing    = unit(0, "points"),
            strip.background = element_blank(),
            strip.text       = element_text(face = "bold", size = 12),
            axis.text.x = element_blank(),
            axis.ticks.x = element_blank())
    

    输出:

    【讨论】:

    • 不错的解决方案!也许您可以使用scales = "free_x" 以获得更好的可比性,但我认为这也有点个人选择
    • @starja 我完全同意你的看法。这取决于个人选择。另外,你的回答很好:)
    • 非常感谢鸭子。我必须重新调整轴的比例,但这可以工作。
    【解决方案2】:

    你需要告诉 ggplot 一个动物属于哪个组;那么您可以使用 x 轴上的 group 参数并使用 fill 参数来进一步区分不同的动物。 position = "dodge" 导致条形图彼此相邻。

    library(ggplot2)
    df <- data.frame(animal = c("cat1","cat2","mouse1","mouse2","dog1","dog2"),
                     size=c(3,4,1,2,6,7),
                     group = c("cat", "cat", "mouse", "mouse", "dog", "dog"))
    
    ggplot(df, aes(x = group, y = size, fill = animal)) +
      geom_col(position = "dodge")
    

    reprex package (v0.3.0) 于 2020 年 8 月 23 日创建

    【讨论】:

    • 非常感谢 Starja!这正是我正在寻找的解决方案。我在小插曲中看到有一个群体争论,但不知道它是如何运作的。
    • 很高兴为您提供帮助!如果你不想让动物有不同的颜色,你可以使用group而不是fill;使用geom_col(width = 0.8, position = position_dodge(width = 0.9)),您可以调整间距
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多