为直方图创建图例时遇到问题。我想使用常见图例制作直方图网格。我有两个问题。
每个直方图都有一个显示平均值的geom-vline,而直方图则显示了所有值。我想制作一个图例,该图例显示geom_vline的颜色和直方图的默认灰色填充。我似乎无法做到这一点,因为您可能需要将直方图除以一个因子才能创建一个填充图例。我也不能使用scale_colour_manual()为直方图创建图例。同样,我无法使用scale_fill_manual()
我希望能够使图例在排列的直方图下居中。
下面的代码和输出显示了适用于虹膜数据集的我的直方图
library(ggplot2)
library(mosaic)
library(grid)
library(gridExtra)
data("iris")
setosaHistogram <-ggplot(data=iris)+geom_histogram(mapping=aes(x=Petal.Length,color='Petal Histogram'))+xlab('Petal Length') +
theme(plot.title = element_text(size = 10, face = "bold",hjust = 0.5),legend.position="none") +
ggtitle(paste("Setosa"))+
geom_vline(aes(xintercept = mean(iris[iris$Species=='setosa','Petal.Length']), color = "Species Mean"),linetype=2)+
scale_fill_manual(name = 'Legend',values=C("Petal Histogram"='grey','Species Mean' ="red"))
versicolorHistogram <-ggplot(data=iris)+geom_histogram(mapping=aes(x=Petal.Length,color='Petal Histogram'))+xlab('Petal Length') +
theme(plot.title = element_text(size = 10, face = "bold",hjust = 0.5),legend.position="none") +
ggtitle(paste("Versicolor"))+
geom_vline(aes(xintercept = mean(iris[iris$Species=='versicolor','Petal.Length']), color = "Species Mean"),linetype=2)+
scale_fill_manual(name = 'Legend',values=C("Petal Histogram"='grey','Species Mean' ="red"))
virginicaHistogram <-ggplot(data=iris)+geom_histogram(mapping=aes(x=Petal.Length,color='Petal Histogram'))+xlab('Petal Length') +
theme(plot.title = element_text(size = 10, face = "bold",hjust = 0.5),legend.position="none") +
ggtitle(paste("Virginica"))+
geom_vline(aes(xintercept = mean(iris[iris$Species=='virginica','Petal.Length']), color = "Species Mean"),linetype=2)+
scale_fill_manual(name = 'Legend',values=C("Petal Histogram"='grey','Species Mean' ="red"))
g <- ggplotGrob(setosaHistogram +
theme(legend.position = 'bottom'))$grobs
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
arrangedPlots<-grid.arrange(setosaHistogram,versicolorHistogram,virginicaHistogram,legend,ncol=3, nrow=2)