【问题标题】:Add legend to geom_density R [duplicate]将图例添加到 geom_density R [重复]
【发布时间】: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') 

我做错了什么吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    理想情况下,您的数据应该是每行一个观察值(也称为“长”数据),以正确利用 ggplot2。这是首先使用tidyr::gather 转换数据的示例。将自动添加带有fillcolor 美学的图例。

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

    【讨论】:

    • 太棒了。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2019-03-05
    相关资源
    最近更新 更多