【问题标题】:How to sort results in ggplot according to grouping variable如何根据分组变量对ggplot中的结果进行排序
【发布时间】:2014-10-05 10:18:38
【问题描述】:

我使用以下代码创建了一个条形图,每个条形都根据其所属的组进行着色。

library("ggplot2")
df <- data.frame(ID=c(5,2,3,6,1,4),Score=c(24.8,33.2,55.21,19.21,41.99,15.23),Gender=c("Man","Woman","Woman","Man","Man","Woman"))
ggplot(df, aes(x=ID, y=Score, color=Gender)) + geom_bar(stat="identity")

这会生成以下图表

现在,我想要实现的是对条形出现的顺序进行排序,主要在性别变量上,次要在 ID 变量上。我在 StackExchange 上搜索过答案,但据我所知,它们中的大多数只处理对 y 变量进行排序。

(请注意,这是一个最小的示例,而我的实际示例非常庞大。因此,我想找到一种方法来订购我不需要的所有东西,例如,手动输入每个 ID 号。 )

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    你可以使用interaction来做到这一点(为了更好地区分男人和女人,我使用fill而不是color):

    ggplot(df, aes(x=interaction(ID,Gender), y=Score, fill=Gender)) + 
      geom_bar(stat="identity") +
      scale_x_discrete("ID",breaks=interaction(df$ID,df$Gender),labels=df$ID) +
      theme_bw() +
      theme(axis.title = element_text(size=14,face="bold"), axis.text = element_text(size=12))
    

    这给出:


    作为替代方案,您也可以使用分面:

    ggplot(df, aes(x=factor(ID), y=Score, fill=Gender)) + 
      geom_bar(stat="identity") +
      scale_x_discrete("ID",breaks=df$ID,labels=df$ID) +
      facet_grid(.~Gender, scales="free_x") +
      guides(fill=FALSE) + theme_bw() +
      theme(axis.title=element_text(size=14,face="bold"), axis.text=element_text(size=12),
            strip.text=element_text(size=12,face="bold"), strip.background=element_rect(fill=NA,color=NA))
    

    给出:

    【讨论】:

    • 谢谢!对漂亮造型的额外赞誉!
    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多