将图例添加到 geom_density R [重复]
Posted
技术标签:
【中文标题】将图例添加到 geom_density R [重复]【英文标题】:Add legend to geom_density R [duplicate] 【发布时间】:2018-08-15 12:28:29 【问题描述】:我正在使用 Prosper Loan 数据集,并尝试使用 geom_density 在同一个图中显示两个变量。 问题是,当我尝试包含 lengend 以显示粉红色区域的变量名和深色区域的变量名时,它不起作用。
library(ggplot2)
EstimatedLoss <- c(0.5, 0.2,0.3,0.4,0.8,0.5, 0.2,0.3,0.4,0.8)
EstimatedEffectiveYield <- c(0.10, 0.15,0.18,0.20,0.8,0.15, 0.13,0.22,0.22,0.25)
prosper_loan <- data.frame(EstimatedLoss,EstimatedEffectiveYield)
ggplot(data = prosper_loan)
geom_density(aes(EstimatedLoss * 100), color = '#e1b582', fill = '#e1b582', alpha = 0.5, show.legend = TRUE ) +
geom_density(aes(EstimatedEffectiveYield * 100), color = '#a2b285',fill = '#a2b285', alpha = 0.7, linetype = 3, size = 1, show.legend = TRUE) +
scale_y_continuous(name = "Density")+
scale_x_continuous(name = "Estimate loss and effective yield in percentage") +
ggtitle('Density from the Estimated loss and effective yield in percentage')
我做错了什么吗?
【问题讨论】:
【参考方案1】:理想情况下,您的数据应该是每行一个观察值(也称为“长”数据),以正确利用 ggplot2
。这是首先使用tidyr::gather
转换数据的示例。将自动添加带有fill
或color
美学的图例。
library(ggplot2)
library(tidyr)
library(magrittr)
EstimatedLoss <- c(0.5, 0.2,0.3,0.4,0.8,0.5, 0.2,0.3,0.4,0.8)
EstimatedEffectiveYield <- c(0.10, 0.15,0.18,0.20,0.8,0.15, 0.13,0.22,0.22,0.25)
prosper_loan <- data.frame(EstimatedLoss, EstimatedEffectiveYield) %>%
gather(key, value, EstimatedLoss:EstimatedEffectiveYield)
ggplot(data = prosper_loan) +
geom_density(aes(value * 100, fill = key, color = key), alpha = 0.5) +
scale_fill_manual(values = c('#e1b582', '#a2b285')) +
scale_color_manual(values = c('#e1b582', '#a2b285')) +
scale_y_continuous(name = "Density")+
scale_x_continuous(name = "Estimate loss and effective yield in percentage") +
ggtitle('Density from the Estimated loss and effective yield in percentage')
【讨论】:
太棒了。非常感谢以上是关于将图例添加到 geom_density R [重复]的主要内容,如果未能解决你的问题,请参考以下文章
将 vline 添加到 geom_density 和平均 R 的阴影置信区间
R语言使用ggplot2包使用geom_density()函数绘制分组密度图(线条色彩添加均值线)实战(density plot)
R语言使用ggplot2包使用geom_density()函数绘制分组密度图(添加直方图分组颜色配置)实战(density plot)
R语言使用ggplot2包使用geom_density()函数绘制分组密度图(填充色配置半透明填充色添加均值线)实战(density plot)