ggplot2图形顺序按分组变量而不是按字母顺序

ggplot2 graphic order by grouped variable instead of in alphabetical order

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

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

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

也许您可以使用 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())

输出: