ヒストグラムが密度でオーバーレイされるプロットを作成する必要があります。ここに私の結果はこれまでにいくつかの例のデータを使用している:ggplot2:オーバーレイされたプロットの凡例シンボルを調整する
library("ggplot2")
set.seed(1234)
a <- round(rnorm(10000, 5, 5), 0)
b <- rnorm(10000, 5, 7)
df <- data.frame(a, b)
ggplot(df) +
geom_histogram(aes(x = a, y = ..density.., col = "histogram", linetype = "histogram"), fill = "blue") +
stat_density(aes(x = b, y = ..density.., col = "density", linetype = "density"), geom = "line") +
scale_color_manual(values = c("red", "white"),
breaks = c("density", "histogram")) +
scale_linetype_manual(values = c("solid", "solid")) +
theme(legend.title = element_blank(),
legend.position = c(.75, .75),
legend.text = element_text(size = 15))
残念ながら、私は適切に凡例のシンボルを変更する方法を見つけ出すことはできません。 最初の記号は比較的太い赤線で、2番目の記号は中央の白線のない青色のボックスにする必要があります。いくつかのインターネット調査に基づき
は、私がscale_linetype_manual
に異なるものを変更しようと、さらに私はoverride.aes
を使用しようとしましたが、私は、この特定の場合にはそれを使用しなければならない方法を見つけ出すことができませんでした。
EDIT - ここは、以下の非常に有用回答に基づいて最適なソリューションです。
ggplot(df) +
geom_histogram(aes(x = a, y = ..density.., linetype = "histogram"),
fill = "blue",
# I added the following 2 lines to keep the white colour arround the histogram.
col = "white") +
scale_linetype_manual(values = c("solid", "solid")) +
stat_density(aes(x = b, y = ..density.., linetype = "density"),
geom = "line", color = "red") +
theme(legend.title = element_blank(),
legend.position = c(.75, .75),
legend.text = element_text(size = 15),
legend.key = element_blank()) +
guides(linetype = guide_legend(override.aes = list(linetype = c(1, 0),
fill = c("white", "blue"),
size = c(1.5, 1.5))))
ありがとう、それは完璧な解決策でした!あなたのコードに2行追加しました。ヒストグラムを白色に保ちたいからです(上記の編集の記事を参照)。 – JSP