问题描述
我遇到了 ggpairs
中消失的图例问题。
我在下三角 ggpairs
图的顶部添加了一个图例,如下所示。
首先我创建了一个没有图例的 ggpairs
图,然后我去掉了我想要的图例和临时图,并用 ggpairs
将它放置在 putPlot
图中。在我尝试修改使图例消失的主题之前,它运行良好。
# 1 produce graph without legend
library(Ggally)
library(ggplot2)
plotwithoutlegend <-ggpairs(
iris,columns=1:4,switch="both",upper="blank",mapping=aes(color = Species,shape= Species,fill=Species,alpha=0.5)
)
#2 grab the legend from a graph with the legend I want (without alpha).
auxplot <- ggplot(iris,aes(x=Petal.Length,y=Petal.Width,color=Species,shape=Species,fill=Species)) + geom_point()
mylegend <- grab_legend(auxplot)
# 3 place the legend in the ggpairs grid with putPlot
graph1 <- putPlot(plotwithoutlegend,mylegend,3,4)
show(graph1)
但是,如果我更改主题的某些方面,图例就会消失。
graph2 <- graph1 +theme(strip.background =element_blank(),strip.placement = "outside")
show(graph2)
更改主题后图例消失:
解决方法
我遇到了类似的问题。我认为您需要使用 My.Sd()
。查看我的解决方案。
library(grid)
,
在这里学习:Legend using ggpairs
# first run your code until
graph2 <- graph1 +theme(strip.background =element_blank(),strip.placement = "outside")
# then run this code
colidx <- c(3,5,6,7)
for (i in 1:length(colidx)) {
# Address only the diagonal elements
# Get plot out of plot-matrix
inner <- getPlot(graph2,i,i);
# Add ggplot2 settings (here we remove gridlines)
inner <- inner + theme(panel.grid = element_blank()) +
theme(axis.text.x = element_blank())
# Put it back into the plot-matrix
graph2 <- putPlot(graph2,inner,i)
for (j in 1:length(colidx)){
if((i==1 & j==1)){
# Move the upper-left legend to the far right of the plot
inner <- getPlot(graph2,j)
inner <- inner + theme(legend.position=c(length(colidx)-0.25,0.50))
graph2 <- putPlot(graph2,j)
}
else{
# Delete the other legends
inner <- getPlot(graph2,j)
inner <- inner + theme(legend.position="none")
graph2 <- putPlot(graph2,j)
}
}
}
# then run this code
show(graph2)