Superimposing Plots

Sometimes, it's easier to compare shapes when we superimpose plots. In the previous example, we created density plots, using facet_wrap to subdivide the data into different credit grades. We can also superimpose plots and use different fill colors to differentiate between them. Consider the following code:

ggplot(df3,aes(x=loan_amnt)) + geom_density(aes(fill=grade),alpha=1/2) + scale_fill_brewer(palette="Dark2") + xlab("Loan Amount") + theme_light()

Here, our geom object is geom_density. The alpha parameter sets the transparency level (we set it to 50%). We chose a customized palette for the fill colors, using the scale_fill_brewer command. Take a look at the following output screenshot:

Get Applied Data Visualization with R and ggplot2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.