【问题标题】:Graph using ggplot bars with repeated categories使用具有重复类别的 ggplot 条形图
【发布时间】:2020-10-15 15:13:10
【问题描述】:

我正在尝试绘制 2020 年每个国家/地区的学校开学、部分开学、在学术休息期间或由于 covid19 关闭的天数。当我使用以下代码时,我得到一个图表,其中每个条形都根据每个国家处于每种状态的时间进行细分。

但是,国家/地区通常会多次更改其状态。例如,阿根廷开始完全开放,然后转为关闭,然后继续学业休息,再次关闭,最后部分开放学校。因此,我希望每个条形图有尽可能多的变化部分(在本例中为五个),而不是只有四个部分对应于四种不同的状态。

df <- data.frame(Country=c("Arg", "Arg", "Arg", "Arg", "Arg"), Status=c("Fully open", "Closed due to covid19", "Academic break", "Closed due to covid19", "Partially open"), days=c(29, 126, 12, 31, 30))

ggplot(df, aes(x = Country, y = days, fill = Status)) + 
  geom_bar(stat='identity') +  coord_flip() + 
  scale_x_discrete(limits = rev)

The graph I get

非常感谢您的帮助! 女同性恋

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    尝试为每个国家/地区的更改次数创建一个变量,如下所示:

    library(ggplot2)
    library(dplyr)
    #Code
    df %>% group_by(Country) %>%
      mutate(Nchange=1:n()) %>%
      ggplot(aes(x = Country, y = days, fill = factor(Nchange))) + 
      geom_bar(stat='identity') +  coord_flip() + 
      scale_x_discrete(limits = rev)+
      labs(fill='Number of changes')
    

    输出:

    为某些更改设置相同的颜色:

    #Code 2
    df %>% group_by(Country) %>%
      mutate(Nchange=1:n()) %>%
      ggplot(aes(x = Country, y = days, fill = factor(Nchange))) + 
      geom_bar(stat='identity') +  coord_flip() + 
      scale_x_discrete(limits = rev)+
      scale_fill_manual(values=c('tomato','green','green','cyan3','magenta'))+
      labs(fill='Number of changes')
    

    输出:

    【讨论】:

    • 谢谢,鸭子!我可以重现代码,但是,有没有办法让类别 2 和 3 具有相同的颜色?这两天代表关闭的日子,但在研究期间的不同时间。我希望它们按原样分开,但颜色相同。
    • @LesbiaMarisG 我添加了一个更新,希望对你有帮助!
    • 鸭子,谢谢你的帮助,它工作得很好。但是,我想知道是否有一种方法可以自动执行相同的操作,因为在这种情况下,每个国家/地区可能有不同的模式,因此每个“更改次数”的含义可能会有所不同。
    • @LesbiaMarisG 这可能是可能的,但需要看到更多数据才能实现这一目标。
    猜你喜欢
    • 2019-03-10
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多