【问题标题】:ggplot2 graphic order by grouped variable instead of in alphabetical orderggplot2图形按分组变量而不是字母顺序排列
【发布时间】:2020-10-10 12:53:46
【问题描述】:

我有一个大型数据框,其中包含有关瑞士某些地区(“州”)报纸的信息。一个最小的、可重现的示例可能如下所示:

dataframe <- data.frame(canton=c("AG","AG","BE","LU","ZH","ZH"),
                        canton_id=c(19,19,2,3,1,1),
                        newspaper=c("AZ","ZOF","BZ","NLZ","AVU","LB"),
                        minimum=c("1999-12-03","2000-10-03","1998-12-03","1998-01-03","2011-04-03","2002-04-03"),
                        maximum=c("2009-09-29","2018-11-27","2018-11-27","2017-02-14","2018-11-27","2018-11-27"))

我需要用 ggplot2 绘制一个看起来与这个相似的图形(请忽略黑点,并认为这个图形比可重现示例的结果大得多):

现在,我已经做了什么?我得到的最接近的是以下代码:

ggplot(dataframe) + geom_segment(aes(x=minimum, xend=maximum, y=newspaper, yend=newspaper, size = 1, color = canton)) 

对我的“解决方案”最大的担忧:如果一个州有多个报纸,我需要按该州对它们进行分组,而不是按字母顺序。我需要处理因子吗?

我已经咨询过以下问题:

How do you specifically order ggplot2 x axis instead of alphabetical order?

Order discrete x scale by frequency/value

如果您需要任何进一步的信息,请告诉我。

【问题讨论】:

    标签: r r-factor


    【解决方案1】:

    也许您可以像这样使用facet_grid() 方法按州分组(我使用了您共享的数据):

    library(ggplot2)
    #Code
    ggplot(dataframe) + 
      geom_segment(aes(x=minimum, xend=maximum, y=newspaper,
                       yend=newspaper, size = 1, color = canton),show.legend = F)+
      facet_grid(canton~.,scales='free')+
      theme_classic()+
      theme(strip.background = element_blank())
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      相关资源
      最近更新 更多