私は似たようなスレッドを見ましたが、私の状況に固有のものは何も見ていません。
ggplot2の塗りつぶし棒グラフにgeom_lineを追加したいと思います。ベクトルとして重ね合わせたい値があります。すべての値を同じデータフレームにマージせずにこれを行う簡単な方法はありますか?
関連する場合は私のコード:
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を返すで実行できます。オブジェクトとして適用する関数を作成しましたが、無名関数として作成することは可能です。
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))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加