migdal menora
migdal menora

Reputation: 167

How to plot two density curves of two continuous variables on the same chart

I'm new to R so I hope that my question is not too simple.I'm trying to plot two density curves of two continuous variables: LTV1 and LTV2 - on the same plot. Doing each density was simple, I used ggplot2 with this lines of code: qplot(LTV1, data = dat, geom = "density", main="LTV1") and qplot(LTV2, data = dat, geom = "density", main="LTV2") But I didn't find a way to put them on the same plot.Any Idea how can It be done? Here is my data frame example:

dat <- read.table(text = " UserID LTV1 LTV2 
                   123        3        9      
                   654        3        8         
                   658        1        2         
                   333        1        2         
                   455        1        8         
                   857        6        1         
                   542        6        7         
                   785        6        1         
                   357        5        9         
                   963        8        5 
                   444        2        1
                   524        2        2 
                   777        6        2 
                   564        1        1 
                   786        3        9 
                   412        1        4   ",header = TRUE)

Upvotes: 0

Views: 3372

Answers (1)

MrFlick
MrFlick

Reputation: 206586

ggplot perfers it's data in tall format rather than a wide format such as how you have it. The easiest way to convert between the two is with the reshape2 pacakge. In this case, we need the melt() function. How about

ggplot(melt(dat, "UserID"), aes(value, color=variable)) + geom_density() + xlim(-5,15)

enter image description here

Note that we had to manually extend the xlim to get the density to go down to 0. The default is to just zoom into the region where you have observations.

Alternative you could add multiple density layers

ggplot(dat) + 
   geom_density(aes(LTV1, color="LTV1")) + 
   geom_density(aes(LTV2, color="LTV2")) + 
   scale_color_hue(name="Variable")

enter image description here

however this would not scale very well if you had a bunch of columns. It's usually easier to just reshape your data

Upvotes: 4

Related Questions