如何让ggpubr中stat_cor与stat_regline_equation顺序匹配图例?
问题:让ggpubr统计量顺序匹配图例顺序
在R语言中使用ggpubr包的stat_cor和stat_regline_equation函数在ggplot绘图上展示相关系数与回归方程时,已通过scale_color_discrete(breaks = c("NF", "CF", "SF"))重新设置图例变量顺序,但stat_cor和stat_regline_equation的输出顺序未随之调整,需要让系数与方程的顺序匹配图例顺序。
原代码:
ggplot(summeravgs30, aes(AvgNightLST, NightTmp, color = Region)) + geom_point(size = 4, shape = 17) + geom_smooth(method = lm) + labs(x = "Mean Night LST (°C)", y = "Average Night SAT (°C)") + scale_x_continuous(limits = c(22,28)) + scale_y_continuous(limits = c(20,36)) + scale_color_discrete(breaks = c("NF", "CF", "SF")) + stat_cor(aes(color = Region), size = 4, p.accuracy = 0.1, label.x.npc = "left", label.y = c(34.5,33.5,32.)) + theme_bw(base_size = 15) + theme(axis.title.x = element_text(size = 15), axis.title.y = element_text(size = 15)) + stat_regline_equation(size = 4, label.x = c(25, 25, 25), label.y = c(22.5,21.5,20.5)) + theme(legend.position = "bottom")
解决方案
问题根源在于:stat_cor和stat_regline_equation是按照数据中Region变量的因子水平顺序来分组计算和输出统计量的,仅通过scale_color_discrete(breaks)只是调整了图例的显示顺序,并没有改变数据内部的分组顺序。因此需要先将Region转换为指定水平顺序的因子,再进行绘图。
步骤1:预处理数据,设置因子水平
在绘图前,将Region列转换为因子,并指定水平顺序为c("NF", "CF", "SF"):summeravgs30$Region <- factor(summeravgs30$Region, levels = c("NF", "CF", "SF"))步骤2:修改绘图代码
此时可以保留scale_color_discrete(breaks)(可选,因为因子水平已经指定了顺序,图例默认会按这个顺序显示),统计量的输出顺序会自动匹配因子水平,对应label.y的位置也会正确对应每个分组:ggplot(summeravgs30, aes(AvgNightLST, NightTmp, color = Region)) + geom_point(size = 4, shape = 17) + geom_smooth(method = lm) + labs(x = "Mean Night LST (°C)", y = "Average Night SAT (°C)") + scale_x_continuous(limits = c(22,28)) + scale_y_continuous(limits = c(20,36)) + # 因子水平已指定,breaks可以省略,也可以保留确保图例顺序一致 scale_color_discrete(breaks = c("NF", "CF", "SF")) + stat_cor(aes(color = Region), size = 4, p.accuracy = 0.1, label.x.npc = "left", label.y = c(34.5,33.5,32.)) + theme_bw(base_size = 15) + theme(axis.title.x = element_text(size = 15), axis.title.y = element_text(size = 15)) + stat_regline_equation(size = 4, label.x = c(25, 25, 25), label.y = c(22.5,21.5,20.5)) + theme(legend.position = "bottom")
这样修改后,stat_cor和stat_regline_equation的输出顺序就会和图例顺序一致,每个分组的统计量位置也会正确对应。
内容的提问来源于stack exchange,提问作者muse
相关产品推荐
相关产品推荐

