r - 为直方图的垂直线添加图例
问题描述
我正在尝试为我正在创建的图表添加图例。这个想法是比较偏斜和对称分布的平均值和中位数。这是我目前拥有的代码,但是
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()
我只想在旁边有个传说,说红色是“平均值”,黄色是“中位数”。
谢谢!
解决方案
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()
如果您有任何其他麻烦,请告诉我,再次抱歉让您误入歧途!
推荐阅读
- surveymonkey - How to replicate more than one Survey from SurveyMonkey using Stitch?
- php - How to use the method name in live template variables?
- python - Enforcing a max limit on the count of a given process
- git - git hook 中的 git pull/fetch/checkout 无法找到正确的存储库目录
- excel - Excel VBA查找,用字符串中的日期替换纪元时间戳
- java - How can some methods be triggered in java without being called at all
- flutter - 颤振不支持动画旋转
- javascript - 在浏览器的开发工具中显示 \n 和 \r\n 字符
- jqgrid - JQGrid 动态创建列标题
- javascript - 当同时更新 2 个会话的页面时,数据重复