簡體   English   中英

將 geom_line 添加到 r 中的堆疊條形圖

[英]Add geom_line to stacked barplot in r

我看過類似的帖子,但沒有看到任何特定於我的情況的內容。

我想在 ggplot2 的填充條形圖中添加 geom_line。 我有要疊加為向量的值。 有沒有一種簡單的方法可以做到這一點,而無需將所有值合並到同一個 dataframe 中?

我的代碼(如果相關):

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

在此處輸入圖像描述

對於 plot 線, geom_line必須事先計算好y坐標。 這可以通過返回 data.frame 的aggregate來完成。 我已經編寫了 function 以用作 object,但可以將其編寫為匿名 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM