如何将gratia::compare_smooths生成的图例强制置于底部?
解决gratia包compare_smooths绘图图例无法置于底部的问题
问题原因
gratia的draw()方法默认使用theme_gratia()主题,该主题默认将图例置于右侧。直接叠加theme(legend.position = "bottom")可能因主题元素优先级问题未生效,需要明确覆盖主题设置或在draw()中直接指定自定义主题。
解决方案
方案1:在draw()中直接指定自定义主题
在调用draw()时,直接传入包含图例位置设置的主题,确保样式生效:
library(tidyverse) library(gratia) library(mgcv) library(ggpubr) gam1 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(cyl >= 6)) gam2 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(cyl < 6)) gam3 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(qsec >= 18)) gam4 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(qsec < 18)) # 在draw中指定主题,设置图例在底部并横向排列 plot1 <- draw(compare_smooths(gam1,gam2), theme = theme_gratia() + theme(legend.position = "bottom", legend.direction = "horizontal")) plot2 <- draw(compare_smooths(gam3,gam4), theme = theme_gratia() + theme(legend.position = "bottom", legend.direction = "horizontal")) gamplot <- ggarrange(plotlist = list(plot1,plot2),ncol = 2) gamplot
方案2:全局设置主题(所有绘图自动应用)
通过theme_set()全局修改gratia主题的图例位置,后续所有draw()生成的图都会自动应用该设置:
library(tidyverse) library(gratia) library(mgcv) library(ggpubr) # 全局修改gratia主题的图例位置 theme_set(theme_gratia() + theme(legend.position = "bottom", legend.direction = "horizontal")) gam1 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(cyl >= 6)) gam2 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(cyl < 6)) gam3 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(qsec >= 18)) gam4 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(qsec < 18)) plot1 <- draw(compare_smooths(gam1,gam2)) plot2 <- draw(compare_smooths(gam3,gam4)) gamplot <- ggarrange(plotlist = list(plot1,plot2),ncol = 2) gamplot
方案3:使用主题替换语法强制覆盖
若直接叠加主题不生效,可使用%+replace%强制替换主题元素:
library(tidyverse) library(gratia) library(mgcv) library(ggpubr) gam1 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(cyl >= 6)) gam2 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(cyl < 6)) gam3 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(qsec >= 18)) gam4 <- gam(mpg ~ am + s(hp),data = mtcars |> filter(qsec < 18)) plot1 <- draw(compare_smooths(gam1,gam2)) + theme_gratia() %+replace% theme(legend.position = "bottom", legend.direction = "horizontal") plot2 <- draw(compare_smooths(gam3,gam4)) + theme_gratia() %+replace% theme(legend.position = "bottom", legend.direction = "horizontal") gamplot <- ggarrange(plotlist = list(plot1,plot2),ncol = 2) gamplot
补充说明
compare_smooths仅负责生成平滑项的对比数据,不处理绘图样式,因此图例位置的调整需要通过draw()的主题参数或后续ggplot主题设置来实现。
内容的提问来源于stack exchange,提问作者flâneur
相关产品推荐
相关产品推荐

