答案 0 :(得分:0)
我建议在单独的数据框中计算协方差,并使用协方差数据框中的值自定义色阶:
library(dplyr)
library(ggplot2)
set.seed(999)
d <- data.frame(
x = runif(60, 0, 100),
z = rep(c(0, 1), each = 30)
) %>%
mutate(
y = x + 50 * z + rnorm(60, sd = 50),
z = factor(z)
)
这是基本图,每个值z
都有单独的颜色:
ggplot(d, aes(x = x, y = y, color = z)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE)
现在创建一个包含协方差值的较小数据框:
cov_df <- d %>%
group_by(z) %>%
summarise(covar = round(cov(x, y)))
提取协方差值并存储为字符向量:
legend_text <- as.character(pull(cov_df, covar))
控制色标以达到预期效果:
ggplot(d, aes(x = x, y = y, color = z)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE) +
scale_color_discrete(
"Covariance",
labels = legend_text
)