我想在堆叠的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")
发布于 2019-08-20 04:16:44
您可以将stat_summary
和sum
用于汇总函数:
ggplot(new_data3, aes(year, value)) +
geom_col(aes(fill = model)) +
stat_summary(geom = "line", fun.y = sum, group = 1, size = 2)
结果:
发布于 2019-08-20 04:12:45
您可以通过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)
https://stackoverflow.com/questions/57566548
复制相似问题