user1993416
user1993416

Reputation: 768

Plot several densities in same figure

I would like to plot 4 datasets in the same plot. I have been trying to overlay but data are similar, and they can not be distinguished. I have this code:

plot(density(rnd1[,5]*f),lty = 1,lwd = 1,col="black",xlim=c(0,2750),xlab="minutes",main='Event 5')
par(new=T)
plot(density(fpsdata[,5]*f), type="l",lty = 2,lwd = 2,col="red", xlim=c(0,2750), xlab="", ylab='',axes=F,main='')
par(new=T)
plot(density(rankdata[,5]*f), type="l",lty = 1,lwd = 2,col="blue", xlim=c(0,2750), xlab="", ylab='',axes=F,main='')
par(new=T)
plot(density(graddata[,5]*f), type="l",lty = 4,lwd = 2,col= "green3", xlim=c(0,2750), xlab="", ylab='',axes=F,main='')

The problem is that the four density plots have the same height and that seems strange because I have been plotting the same data with another program and the densities have different heights.

Does anyone know why R makes all density plot the same height when combined in one figure?

Regards

Upvotes: 1

Views: 80

Answers (2)

d.b
d.b

Reputation: 32558

Don't use par(new=T). Instead, create an empty plot and then add lines for each density

#DATA
set.seed(42)
a = rnorm(25)
b = rnorm(25)

#Calculate density
ad = density(a)
bd = density(b)

#Create empty plot so as to accommodate all data
plot(c(ad$x, bd$x), c(ad$y, bd$y), type = "n")

#Add density plots
lines(ad$x, ad$y)
lines(bd$x, bd$y, lty = 2)

enter image description here

Upvotes: 1

eipi10
eipi10

Reputation: 93871

Here's a ggplot2 approach:

library(tidyverse) # Includes ggplot2 and dplyr (the two packages we'll use below)

# Fake data
set.seed(2)
f = 2
df1 = data.frame(value=rnorm(123, 1.1, 2))
df2 = data.frame(value=rnorm(245, 0.8, 2.5))
df3 = data.frame(value=rnorm(211, 1.4, 1.9))

# Stack data frames and plot
bind_rows(setNames(list(df1, df2, df3), c("df1","df2","df3")), .id="source") %>% 
  ggplot(aes(value*f, colour=source)) +
    geom_density() +
    theme_classic()

enter image description here

Upvotes: 1

Related Questions