0

I'm working with the Prosper Loan dataset and I'm trying to show two variable in the same plot using geom_density. The problem, when I try to include the lengend to show the variable name from the pink area and the variable name from the dark area, it doesn't work.

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

Am I doing anything wrong?

1 Answers1

3

Ideally, your data should be one observation per row (aka "long" data) to properly take advantage of ggplot2. Here's an example of first transforming the data using tidyr::gather. A legend will automatically be added with a fill or color aesthetic.

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

enter image description here

Jack Brookes
  • 3,720
  • 2
  • 11
  • 22