2

I am trying to produce a plot with histogram and scatter plot in just one plot using a secondary axis. In detail, here is an example data:

#generate example data

set.seed(1)
a <- rnorm(200,mean=500,sd=35)
data <- data.frame(a = a,
                   b = rnorm(200, mean=10, sd=2),
                   c = c(rep(1,100), rep(0,100)))

# produce a histogram of data$a
hist(a, prob=TRUE, col="grey")

#add a density line
lines(density(a), col="blue", lwd=2)

#scatter plot 
plot(data$a,data$b,col=ifelse(data$c==1,"red","black"))

enter image description here enter image description here

What I want to do is to combine the histogram and scatter plot together. This implies my x-axis will be data$a, my primary y-axis is the frequency/density for the histogram and my secondary y-axis is data$b.

rawr
  • 20,481
  • 4
  • 44
  • 78
89_Simple
  • 3,393
  • 3
  • 39
  • 94
  • Will they be the same scale and/or a transformation of the primary on the y-axis? If not, you might want to read Hadley Wickhams explanation to why this is not a good idea. [Good post about why you shouldn't](http://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-another-y-axis-on-the-right) – Ted Mosby Feb 15 '16 at 14:51

2 Answers2

0

Maybe something like this...

# produce a histogram of data$a
hist(a, prob=TRUE, col="grey")

#add a density line
lines(density(a), col="blue", lwd=2)

par(new = TRUE)

#scatter plot 
plot(data$a,data$b,col=ifelse(data$c==1,"red","black"),
     axes = FALSE, ylab = "", xlab = "")
axis(side = 4, at = seq(4, 14, by = 2))
Kota Mori
  • 6,510
  • 1
  • 21
  • 25
0

There's a good blog on this here http://www.r-bloggers.com/r-single-plot-with-two-different-y-axes/.

Basically, as the blog describes you need to do:

par(new = TRUE)
plot(data$a,data$b,col=ifelse(data$c==1,"red","black"), axes = F, xlab = NA, ylab = NA)
axis(side = 4)