简体   繁体   English

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

[英]How to put variables in legend in ggplot2

I want to get the following plot. 我想得到以下情节。 Cov(x,y)的值

So, how would I put a variable ie cov(x,y) as string in legend using ggplot? 那么,如何使用ggplot将变量即cov(x,y)作为字符串放入图例中?

I would recommend calculating the covariance in a separate data frame, and customizing the color scale using the values in the covariance data frame: 我建议在一个单独的数据框中计算协方差,并使用协方差数据框中的值自定义色阶:

Sample Data 样本数据

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 : 这是基本绘图,每个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
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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