I would recommend calculating the covariance in a separate data frame, and customizing the color scale using the values in the covariance data frame:
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)
)
Here is the basic plot, with a separate color for each value of z
:
ggplot(d, aes(x = x, y = y, color = z)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE)
Now create a smaller data frame that contains covariance values:
cov_df <- d %>%
group_by(z) %>%
summarise(covar = round(cov(x, y)))
Extract the covariance values and store as a character vector:
legend_text <- as.character(pull(cov_df, covar))
Control the color scale to achieve your desired outcome:
ggplot(d, aes(x = x, y = y, color = z)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE) +
scale_color_discrete(
"Covariance",
labels = legend_text
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.