Home > Net >  Add two density curves (from separate tables) into same plot (using ggplot in R)
Add two density curves (from separate tables) into same plot (using ggplot in R)

Time:02-05

I have two tables mresm, mresf with a numeric column Total in both tables (different values). Plotting a density plot for either of the two in R can be done in the following way:

mresm %>% ggplot(aes(x = mresm$Total)) geom_density()
mresf %>% ggplot(aes(x = mresf$Total)) geom_density()

However, I want to add both the resulting curves on the same plot to be able to compare them. Have tried a lot of alternatives with no success. Please help!

CodePudding user response:

You could specify inside geom_density the data and aes arguments:

ggplot()   
      geom_density(data = mresm , aes(x = Total))  
      geom_density(data = mres ,  aes(x = Total))

CodePudding user response:

Something like thins should work:

mresm = data.frame(name = rep("mresm", 10), Total = c(1,2,3,4,5,6,7,8,9,10))
mresf= data.frame(name = rep("mresf", 10), Total = c(15,16,17,18,19,20,21,22,23,24))

df = rbind(mresm,mresf)
my_plot =  ggplot(df, aes(x = df$Total, fill=name))   geom_density()
my_plot
  •  Tags:  
  • Related