Home > database >  Combine two density plots in R into one plot
Combine two density plots in R into one plot

Time:04-30

I want to combine two separate density plots I created in Rstudio into one plot that displays both.

I used the following code to create the two separate density plots:

1 # create density plot for total sales
dens_plot_sales <- final_data %>%
drop_na(tot_sales, firm_size) %>%
ggplot() 
geom_density(aes(x = tot_sales, colour = firm_size))  
labs(title = "Density plot of total sales across firm size levels", 
x = "Total sales", y = "Density", col= "Firm size")  
theme_classic()

2 # create density plot for total costs
dens_plot_costs <- final_data %>%
drop_na(tot_costs, firm_size) %>%
ggplot() 
geom_density(aes(x = tot_costs, colour = firm_size))  
labs(title = "Density plot of total costs across firm size levels", 
x = "Total costs", y = "Density", col= "Firm size")  
theme_classic()

How to I combine plot 1 (dens_plot_sales) and plot 2 (dens_plot_costs) into one? (see the plots attached for reference)

Thanks!

CodePudding user response:

# create density plot for total sales and costs
dens_plot_sales <- final_data %>%
drop_na(tot_sales, firm_size) %>%
ggplot() 
geom_density(aes(x = tot_sales, colour = firm_size))  
geom_density(aes(x = tot_costs, colour = firm_size))   # It's that simple
labs(title = "Density plot of total sales and costs across firm size levels", 
x = "Total sales/costs ($)", y = "Density", col= "Firm size")  
theme_classic()

I can't test it fully without knowing what final_data is, but this should work

  • Related