繁体   English   中英

在堆叠的bar_plot顶部画一条线

[英]Draw a line on top of stacked bar_plot

我想在堆积的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")

您可以将stat_summarysum用于摘要功能:

ggplot(new_data3, aes(year, value)) + 
geom_col(aes(fill = model)) + 
stat_summary(geom = "line", fun.y = sum, group = 1, size = 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)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM