【发布时间】:2019-01-21 22:26:19
【问题描述】:
我正在尝试为我正在创建的图表添加图例。这个想法是比较偏斜和对称分布的平均值和中位数。这是我目前拥有的代码,但是
show.legend = TRUE
代码无法完成这项工作。
set.seed(19971222)
sym <- as.data.frame(cbind(c(1:500), rchisq(500, df = 2))) # generate 500 random numbers from a symetric distribution
colnames(sym) <- c("index", "rnum")
sym_mean <- mean(sym$rnum)
sym_med <- median(sym$rnum)
# get into a format that tidyverse likes
central_measures <- as.data.frame(cbind(sym_mean, sym_med))
colnames(central_measures) <- c("mean", "median")
sym %>% ggplot(aes(sym$rnum)) +
geom_histogram(binwidth = 0.4, fill = "steelblue", colour = "navy", alpha = 0.9) +
geom_vline(xintercept = sym_mean, colour = "red", show.legend = TRUE) +
geom_vline(xintercept = sym_med, colour = "yellow", show.legend = TRUE) +
labs(title = "Histogram of 500 Randomly Generated Numbers from the Chi-Squared Distribution",
x = "Value",
y = "Frequency") +
theme_minimal()
我只想在旁边有个图例,说红色是“Mean”,黄色是“Median”。
谢谢!
【问题讨论】:
-
在
aes(color = '<legend_label>')中为您的 vlines 添加颜色,然后添加+ scale_color_manual(values = c("red", "yellow")) -
嗨内特,感谢您的快速回复!我的代码现在看起来像
geom_vline(aes(color = 'Median'), xintercept = sym_med, colour = "yellow", show.legend = TRUE) + scale_color_manual(values = c("red", "yellow"))但它仍然不显示图例
标签: r ggplot2 data-visualization tidyverse