combine histogram with scatter plot in R

感情迁移 提交于 2019-12-23 21:57:57

问题


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"))

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.


回答1:


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))



回答2:


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)


来源:https://stackoverflow.com/questions/35412297/combine-histogram-with-scatter-plot-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!