-1

How can I plot 2 density plots in one output. Here are my codes for the density plot.

#Density Plot
d <- density(dataS)
plot(d, main= "Density plots of Revenue")

o <- density(RemoveOutlier)
plot(o, main= "Density plots of Revenue excluding outliers")

So basically I want to see both plots on one output. And maybe change the color line of each plot and a legend on the top right. Attached is the picture of the 2 plots in R.

image 1

image 2

I am a Student
  • 1,410
  • 3
  • 16
  • 32
  • 1
    try to call `par(mfrow=c(2,1))` before plotting. The question is certainly a dup... – Roman Mar 16 '18 at 08:43
  • 2
    use lines for the second density: `lines(density(o), col = "red")` – missuse Mar 16 '18 at 08:45
  • I actually don't think this is quite a duplicate of the mentioned question. My answer will address why in a moment. It may well be a duplicate, just not of the "plot two graphs at once" question. – MichaelChirico Mar 16 '18 at 08:55
  • How about this [one](https://stackoverflow.com/questions/6939136/how-to-overlay-density-plots-in-r) you edited your self @MichaelChirico; Gavin's comment addresses the issue you might have. – missuse Mar 16 '18 at 08:56
  • 1
    @missuse yes that's perfect. I'll update my answer there and delete the below. – MichaelChirico Mar 16 '18 at 08:58
  • actually, i already added the below answer there xD – MichaelChirico Mar 16 '18 at 08:59

2 Answers2

1

Or instead of the second "plot()" function call, use "lines()", then you get two overlapping density plots.

Lennyy
  • 4,953
  • 2
  • 7
  • 21
  • This approach may not be sufficient. See my answer soon. – MichaelChirico Mar 16 '18 at 08:52
  • I see what you mean. If that is an issue another option to solve this would be to adjust the xlim argument of the plot() call. plot(density(x1), xlim = c(-5,10)) lines(density(x2)) – Lennyy Mar 16 '18 at 10:18
0

If the support of your PDFs is quite spread apart, using lines will not suffice. You'll need to control the range of the calculated values to the density.

Here's an example:

x1 = rnorm(1e5)
x2 = rnorm(1e5, mean = 4)

#looks bad because the support has little overlap
plot(density(x1))
lines(density(x2))

To overcome this, leverage the to and from parameters to density

rng = range(c(x1, x2))
d1 = density(x1, from = rng[1L], to = rng[2L])
d2 = density(x2, from = rng[1L], to = rng[2L])
matplot(d1$x, cbind(d1$y, d2$y), type = 'l', lty = 1L)

Add bells and whistles to taste.

MichaelChirico
  • 31,197
  • 13
  • 98
  • 169