简体   繁体   中英

Draw a line on top of stacked bar_plot

I would like to draw a line (or making points) on top of my stacked bar_plots. As I have no real data points I can refer to (only the spereated values and not the sum of them) I don't know how I can add such line. The Code produce this plot: 在此处输入图片说明

I want to add this black line(my real data are not linear):

在此处输入图片说明

 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")

You can use stat_summary and sum for the summary function:

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

Result:

在此处输入图片说明

You could get sum by year and plot it with new 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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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