Search code examples
rdata-visualizationdata-sciencedata-analysisdata-cleaning

How to create a matrix of density plots in R


enter image description hereInstead of creating different different plots for a data-frame, I want to create a matrix of density plots for a data frame where I can see all the columns in one plot. For creating it separately I am using below code. How can I get all the columns in one plot?

loan_amnt <- density(out_data$loan_amnt)
plot(loan_amnt, main="Loan Amount")
polygon(loan_amnt, col="red", border="blue")

enter image description here


Solution

  • You can combine gather() from library dplyr, and facet_grid() or facet_wrap() from ggplot2.

    With gather, you regroup all your column names in one variable (values of these variables in a second variable) and then your build your plot with ggplot and by using facet_wrap, it will create one plot for each level of your variable with the column names.