【问题标题】:Draw a line on top of stacked bar_plot在堆积条形图的顶部画一条线
【发布时间】:2019-08-20 04:00:28
【问题描述】:

我想在堆叠的 bar_plots 上画一条线(或做点)。由于我没有可以参考的真实数据点(只有分散的值而不是它们的总和)我不知道如何添加这样的行。代码产生了这个情节:

我想添加这条黑线(我的真实数据不是线性的):

 library(tidyverse)
 ##Create some fake data
 data3 <- tibble(
  year = 1991:2020,
  One = c(31:60),
  Two = c(21:50),
  Three = c(11:40)   
  )

 ##Gather the variables to create a long dataset
 new_data3 <- data3 %>%
 gather(model, value, -year)

 ##plot the data
 ggplot(new_data3, aes(x = year, y = value, fill=model)) + 
 geom_bar(stat = "identity",position = "stack")

【问题讨论】:

    标签: r ggplot2 plot bar-chart


    【解决方案1】:

    您可以将stat_summarysum 用于汇总功能:

    ggplot(new_data3, aes(year, value)) + 
    geom_col(aes(fill = model)) + 
    stat_summary(geom = "line", fun.y = sum, group = 1, size = 2)
    

    结果:

    【讨论】:

      【解决方案2】:

      您可以通过year 获得sum 并使用新的geom_line 绘制它

      library(dplyr)
      library(ggplot2)
      
      newdata4 <- new_data3 %>%
                    group_by(year) %>%
                    summarise(total = sum(value))
      
      ggplot(new_data3, aes(x = year, y = value, fill=model)) + 
         geom_bar(stat = "identity",position = "stack") + 
         geom_line(aes(year, total, fill = ""), data = newdata4, size = 2)
      

      【讨论】:

        猜你喜欢
        • 2020-09-14
        • 1970-01-01
        • 1970-01-01
        • 2011-03-24
        • 2014-06-05
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多