简体   繁体   中英

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?

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 :

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.

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