【问题标题】:ggplot combine dodge with stacked barplotggplot 将闪避与堆叠条形图相结合
【发布时间】:2021-07-29 12:54:58
【问题描述】:

我想在 ggplot 中结合堆叠和闪避风格的条形图。这段代码我很接近它:

dates_g <- as.Date(c("2020-03-30","2020-03-30", "2020-04-30","2020-04-30", "2020-05-30","2020-05-30"))
value_x <- c(1, 2, 4, 1.4, 3.2, 1.3)
value_y <- c(1.2, 3, 4.6, 1, 3, 1)
ID <- c("A", "B", "A", "B", "A", "B")

results <- data.frame(dates_g, value_x, value_y, ID)

barwidth = 13
bar_comparison <- ggplot() + 
  geom_bar(data = results[,c(1,2,4)],
           mapping = aes(x=dates_g , y=value_x, fill=ID),
           stat ="identity",
           position = "stack",
           width = barwidth)  +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  geom_bar(data = results[,c(1,3,4)],
           mapping = aes(x=dates_g + barwidth + 0.01 , y=value_y, fill=ID),
           stat ="identity",
           position = "stack",
           width = barwidth) +
  xlab("Date") + ylab("Value (in millions)")

ggplotly(bar_comparison)

结果是:

我仍然对两件事不满意:我希望日期在两个栏之间(但这是一个小问题),然后我真的希望对于每个日期,两个栏都有不同的颜色条:例如,我想让左边的条为绿色(深绿色和浅绿色),右边的条为蓝色(深蓝色和浅蓝色)。有可能吗?

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    这至少是主要问题的解决方案。 我建议使用facet_wrap。 为此准备数据 -> 以长格式引入数据,提取日期的月份名称(我为此使用 lubridate),然后使用 ggplot 进行绘图

    library(lubridate)
    results_long <- results %>% 
      pivot_longer(
        cols = starts_with("value"), 
        names_to = "Names",
        values_to = "Values"
      ) %>% 
      mutate(dates_name = parse_number(as.character(dates_g)),
             dates_name = month(ymd(dates_g), label = TRUE))
    
    ggplot(results_long, aes(x = Names, y = Values, fill = ID)) + 
      geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ dates_name) +
      theme_bw()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 2017-07-21
      • 2018-04-01
      相关资源
      最近更新 更多