繁体   English   中英

如何在ggplot2中的图例中放置变量

[英]How to put variables in legend in ggplot2

我想得到以下情节。 Cov(x,y)的值

那么,如何使用ggplot将变量即cov(x,y)作为字符串放入图例中?

我建议在一个单独的数据框中计算协方差,并使用协方差数据框中的值自定义色阶:

样本数据

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM