以下の例のように、積み重ねられたバープロットがあります。
各バーに異なる値で、各バーに1セットまたは2セットの水平線(色と線種を指定)を追加し、これらを凡例に追加します。
Titanic.df <- as.data.frame(Titanic)
Titanic.ag <- aggregate( Freq ~ Sex + Class + Age, data=Titanic.df, sum, subset = Survived == "Yes")
bars <- rep(c(0.5, NA, 0.7, NA, 0.6, NA, 0.9, NA), 2)
ggplot(Titanic.ag, aes(x = Class, y = Freq, fill = Sex)) +
geom_bar(position = "fill", stat = "identity") +
facet_grid(~Age) +
geom_errorbar(aes(y = bars, ymin = bars, ymax = bars, col = "Ref1")) +
scale_fill_manual(values = c("darkgreen", "darkblue") ) +
labs(col = "Reference",
fill= "",
y = "Proportion",
x = "Class")
いくつかの質問で提案されているようにgeom_errorbar()を使用しようとしましたが、2つの問題が発生します。
エラーバーの値のベクトルを追加すると、ggplotはデータフレームと同じ長さ(たとえば、Titanic.agの16)を期待しますが、スタックされているのは8本のバーだけです。これが、bars
上記でNAを使用した理由です。代替手段はありますか?
さらに重要なのは、色と線種を制御したいのですが、これらをgeom_bar()に追加すると、凡例が失われます。例えば
geom_errorbar(aes(y = bars, ymin=bars, ymax=bars, col = "Ref1"), col = "red", linetype = 2)
geom_segment()は代替手段ですか?
タイプミスを編集し、水平線のさまざまな値を明確にしました。
上記の答えは伝説を生み出しません。線種と色は変わりますが、元の質問でもこれを示しました。いくつか検索した後、凡例を追加する方法を見つけたので、ここに投稿しました。
library(ggplot2)
Titanic.df <- as.data.frame(Titanic)
Titanic.ag <- aggregate( Freq ~ Sex + Class + Age, data=Titanic.df, sum, subset = Survived == "Yes")
bars <- rep(c(0.5, NA, 0.7, NA, 0.6, NA, 0.9, NA), 2)
ggplot(Titanic.ag, aes(x = Class, y = Freq, fill = Sex)) +
geom_bar(position = "fill", stat = "identity") +
facet_grid(~Age) +
geom_errorbar(aes(y = bars, ymin = bars, ymax = bars, col = "Ref1"), linetype = 2, size = 1) +
scale_fill_manual(values = c("darkgreen", "darkblue") ) +
scale_colour_manual(name='', values=c("Ref1" = "darkred"), guide ="legend") +
guides(col = guide_legend(override.aes = list(linetype=2), title = "Reference")) +
labs(fill= "",
y = "Proportion",
x = "Class")
これは、さらにgeom_errorbar()を追加するように適合させることができます。
私はまだ原因でNASとの仕事のラウンドに警告を取得するgeom_errorbar()
ためのベクターy
、ymin
およびymax
、これはより多くの面で複雑になりますが、それは動作します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加