问题描述
我看过类似的话题,但没有发现任何适合我的情况的
I have looked a similar threads but haven't seen anything specific to my situation.
我想在ggplot2的填充条形图中添加geom_line.我有要叠加为向量的值.有没有一种简单的方法可以将所有值都合并到同一数据帧中呢?
I want to add a geom_line to a fill barchart in ggplot2. I have the values I want to superimpose as a vector. Is there a simple way to do this without merging all the values into the same dataframe?
我的代码(如果相关):
my code if relevant:
ggplot(df_region, aes(fill=as.factor(Secondary1), y=Total, x=Year)) +
geom_bar(position="fill", stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
labs(y="Percentage of jobs", x = "Year") + scale_fill_manual(values=c("#8DA0CB" , "#E78AC3" )) + theme(axis.title.x = element_text( size = 14),axis.title.y = element_text(size =14))
推荐答案
要绘制线条, geom_line
必须具有预先计算的 y
坐标.这可以通过 aggregate
完成,该方法返回一个data.frame.我已经编写了要用作对象的函数,但是可以将其编写为匿名函数.
To plot the line, geom_line
must have the y
coordinates computed beforehand. This can be done with aggregate
, which returns a data.frame. I have written the function to be applied as an object, but it is possible to write it as an anonymous function.
f <- function(x) x[2]/sum(x)
df_line <- aggregate(Total ~ Year, df_region, f)
然后,在 geom_line
中设置 inherit.aes = FALSE
.
ggplot(data=df_region, aes(x=Year, y=Total, fill=as.factor(Secondary1))) +
geom_bar(position="fill", stat="identity") +
geom_line(data = df_line, mapping = aes(x = Year, y = Total), color = "red", inherit.aes = FALSE) +
theme(legend.position="bottom") +
theme(legend.title=element_blank()) +
labs(y="Percentage of jobs", x = "Year") +
scale_fill_manual(values=c("#8DA0CB", "#E78AC3")) +
theme(axis.title.x = element_text(size = 14),
axis.title.y = element_text(size = 14))
测试数据
set.seed(2020)
df_region <- data.frame(Year = rep(2011:2019, each = 2),
Secondary1 = rep(c("a", "b"), length(2011:2019)),
Total = sample(10, 18, TRUE))
这篇关于将geom_line添加到R中的堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!