首页 > 解决方案 > 为直方图的垂直线添加图例

问题描述

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

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

我只想在旁边有个传说,说红色是“平均值”,黄色是“中位数”。

谢谢!

标签: rggplot2data-visualizationtidyverse

解决方案


Heyyy,对不起,我有点偏离了方向,我的第一个建议有点偏离。这是实现为中心性度量添加图例的目标的一种方法。

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

在此处输入图像描述

如果您有任何其他麻烦,请告诉我,再次抱歉让您误入歧途!


推荐阅读