重新排序 stat_cor 和 stat_regline_equation 中的行以匹配图例

问题描述 投票:0回答:1

我正在使用

stat_cor
中的
stat_regline_equation
ggpubr
在 R 中的 ggplot 上绘制系数和方程。我已经使用
scale_color_continuous
重新排序了图例中的变量,但它看起来是
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")

得到: enter image description here

r ggplot2 ggpubr
1个回答
0
投票

正如 @Edward 在评论中所指出的,您必须将映射到

color
的变量转换为根据您所需的顺序设置级别的因子。

使用基于

mtcars
的最小表示:

library(ggplot2)
library(ggpubr)

# Example data
summeravgs30 <- mtcars[c("cyl", "hp", "mpg")]
names(summeravgs30) <- c("Region", "AvgNightLST", "NightTmp")
summeravgs30$Region <- as.character(
  factor(
    summeravgs30$Region,
    labels = c("NF", "CF", "SF")
  )
)

# Convert to a factor
summeravgs30$Region <- factor(summeravgs30$Region, c("NF", "CF", "SF"))

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)) +
  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")
#> `geom_smooth()` using formula = 'y ~ x'

© www.soinside.com 2019 - 2024. All rights reserved.