【问题标题】:Adding a legend for vertical lines of histograms为直方图的垂直线添加图例
【发布时间】: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 = '&lt;legend_label&gt;') 中为您的 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


【解决方案1】:

嘿嘿,抱歉,我有点跑题了,我的第一个建议有点不对劲。这是实现为中心性度量添加图例的目标的一种方法。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2011-08-27
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多