首页 > 解决方案 > 带折线的分组堆积条形图

问题描述

试图获得一个图表,其中包含按不同年份和类别堆叠的条形图,按月份分组,顶部有两条线(每年一条线)。图表最终应该类似于下面在 Excel 中制作的图表:

带折线的分组堆积条形图

下面的示例数据:

df <- structure(list(cat1 = c(813392.8465, 835451.0911, 879161.0253, 
494869.9946, 354418.5719, 434533.4505, 552825.1066, 536814.0529, 
547884.7895, 599198.3688, 618577.5224, 770886.8232, 778509.3569, 
891851.6837), cat2 = c(1366565.153, 1338401.909, 1392746.975, 
644118.0054, 589076.4281, 647747.5495, 759816.8934, 810880.9471, 
973262.2105, 710650.6312, 692854.4776, 796064.1768, 734960.6431, 
756644.3163), line_data = c(3973, 3829, 3802.1, 2970.7, 1877.8, 
2378, 2578, 2378, 3245, 2955, 2893, 2999, 2950.1, 3035), Month = structure(c(1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L), .Label = c("Jan", 
"Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", 
"Nov", "Dec"), class = c("ordered", "factor")), Year = structure(c(2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L), .Label = c("2019", 
"2020", "2021"), class = "factor")), row.names = c(NA, -14L), class = "data.frame")

到目前为止,我已经设法通过使用 facet wrap 获得堆叠和分组,但我无法获得一条线来跨越所有方面并正确显示。如果我删除分面包裹,我可以与线堆叠或分组,但不能同时进行所有三个。请参阅下面的代码

require(tidyverse)
require(lubridate)
require(reshape2)

    df <- df %>% melt(id.vars = c("Month", "Year", "line_data"), variable.name = "stack_category", value.name = "stack_category_value")
    
    ggplot(df, aes(fill = stack_category, y=stack_category_value, x=Year)) +
      geom_bar(position="stack", stat="identity", width = .9) +
      facet_wrap(~Month, nrow=1, strip.position = "bottom") +
      geom_line(aes(y = 625*line_data, group = Year, colour = Year), size = 1.5) +
      scale_y_continuous(sec.axis = sec_axis(~./625, name = "line_data")) +
      labs(y = "stack_category_value", x = NULL, title = "Category and Line Data", fill = "Category Data", colour = "Line Data") +
      theme(legend.position = "bottom", plot.title = element_text(size = 20, face= "bold", hjust = .5)) +
      theme(strip.background = element_blank(), strip.placement = "outside", panel.spacing = unit(0, "mm")) +
      theme(panel.background = NULL, panel.grid = element_line(linetype = "blank"), panel.grid.major.y = element_line(linetype = "solid", color = "black"))
      

让一条线遍历所有方面并看起来连续似乎是一个非首发,但我不确定如何优雅地实现分组和堆叠。到目前为止,我的图表如下所示:

代码输出示例

标签: rggplot2

解决方案


推荐阅读