[英]How to put variables in legend in ggplot2
我建議在一個單獨的數據框中計算協方差,並使用協方差數據框中的值自定義色階:
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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.