これはここと同様の質問ですが、私は彼らの解決策を私のために働かせることができませんでした。複数の独立したデータフレームを使用してプロットを生成する場合、ggplot2プロットに凡例を追加したいと思います。
Rで利用可能なデータセットに基づく例を次に示します。
a=longley
b=iris
a$scaled=scale(a$Unemployed,center=TRUE,scale=TRUE)
b$scaled=scale(b$Sepal.Length,center=TRUE,scale=TRUE)
ggplot () +
geom_density(data=a,aes(x=scaled),fill="red",alpha=0.25) +
geom_density(data=b,aes(x=scaled),fill="blue",alpha=0.25) +
scale_colour_manual("",breaks=c("a","b"),values=c("red","blue"))
これに凡例を追加するにはどうすればよいですか?
非常に小さな構文変更が必要です。fill=
パーツを各geomのaes()ステートメントに移動します。
a=longley
b=iris
a$scaled=scale(a$Unemployed,center=TRUE,scale=TRUE)
b$scaled=scale(b$Sepal.Length,center=TRUE,scale=TRUE)
ggplot () +
geom_density(data=a,aes(x=scaled,fill="red"),alpha=0.25) +
geom_density(data=b,aes(x=scaled,fill="blue"),alpha=0.25)
これは単独で機能するはずであり、デフォルトのrカラースキームを提供します。または、本当にデフォルトから色を変更したい場合は、手動スケールを追加できます。ただし、スケールをfill
パラメータに適用する必要があるため、scale_fill_manual
ではなく必ず指定してくださいscale_colour_manual
。
ggplot () +
geom_density(data=a,aes(x=scaled,fill="red"),alpha=0.25) +
geom_density(data=b,aes(x=scaled,fill="blue"),alpha=0.25) +
scale_fill_manual("",breaks=c("a","b"),values=c("red","blue"))
線の色を変更したい場合は、color
美的感覚でそれを行い、scale_color_manual
or scale_colour_manual
(同じこと)オプションを使用できるようになります。
ggplot() +
geom_density(data=a, aes(x=scaled, fill="red", color="yellow"), alpha=0.25) +
geom_density(data=b, aes(x=scaled, fill="blue", color="green"), alpha=0.25) +
scale_fill_manual(values=c("red","blue")) +
scale_color_manual(values=c("yellow", "green"))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加