我在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)这将在所需位置生成带有图例的图形。
更改主题前带有图例的ggpairs图表:

但是,如果我更改了主题的某些方面,图例就会消失。
graph2 <- graph1 +theme(strip.background =element_blank(), strip.placement = "outside")
show(graph2)在改变主题后,传说消失了:

发布于 2021-05-08 05:14:15
我也有过类似的问题。我认为你需要使用library(grid)。请参阅我的解决方案。
# plotwithoutlegend
plotwithoutlegend <- ggpairs(
iris,
columns=1:4,
switch="both",
upper="blank",
mapping=aes(color = Species,
shape= Species,
fill=Species,
alpha=0.5)
)+
theme(strip.background =element_blank(), strip.placement = "outside")
#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)
##### plot legend with plot
grid.newpage()
grid.draw(plotwithoutlegend)
vp = viewport(x=.9, y=.75, width=.35, height=.3) ## control legend position
pushViewport(vp)
grid.draw(mylegend)
upViewport()发布于 2021-05-08 05:13:04
在这里了解到: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, 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, i, j)
inner <- inner + theme(legend.position=c(length(colidx)-0.25,0.50))
graph2 <- putPlot(graph2, inner, i, j)
}
else{
# Delete the other legends
inner <- getPlot(graph2, i, j)
inner <- inner + theme(legend.position="none")
graph2 <- putPlot(graph2, inner, i, j)
}
}
}
# then run this code
show(graph2)

https://stackoverflow.com/questions/67441471
复制相似问题