簡體   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