为直方图的垂直线添加图例

时间:2019-01-21 22:26:20

标签: r ggplot2 data-visualization tidyverse

我正在尝试为要创建的图形添加图例。想法是比较偏斜和对称分布的均值和中位数。这是我目前拥有的代码,但是

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()

我只想在侧面画一个图例,说红色是“平均值”,黄色是“中位数”。

谢谢!

1 个答案:

答案 0 :(得分:2)

嘿,对不起,我被跟踪了一下,而我的第一个建议有些偏离。这是一种实现为中心度度量添加图例的方法。

# use this instead of central_measures
central_values <- data.frame(measurement = c("mean", "median"),
                             value = c(sym_mean, sym_med))

sym %>% ggplot(aes(sym$rnum)) + 
  geom_histogram(binwidth = 0.4, fill = "steelblue", colour = "navy", alpha = 0.9) + 
  geom_vline(data = central_values, aes(xintercept = value, color = measurement)) +
  scale_color_manual(values = c("red", "orange"), name = NULL) +
  labs(title = "Histogram of 500 Randomly Generated Numbers from the Chi-Squared Distribution", 
       x = "Value", 
       y = "Frequency") +
  theme_minimal()

enter image description here

如果您还有其他麻烦,请告诉我,再次对不起您使我误入歧途!

相关问题