用两种不同颜色的随机数叠加

时间:2017-03-10 03:22:19

标签: r plot

我想知道在R thru中是否有一种方法可以在R的单个图中叠加以下两个图?

注意:我需要保留每个情节'显示功能,例如独立运行每个绘图时注意,例如每个绘图中的ylim()必须不同。

这是我的R代码:

# Plot #1:   

yy = rnorm(1000)
xx = seq(-4, 4, len=1000)
plot(xx, yy, ty="p", ylim=c(-4, 4), pch=20)  ## Note ylim() here ##
abline(h=c(0, 3, -3 ), col='green', lwd=3)

# Plot # 2:

y = rcauchy(1000, 0, 1)
x = seq(-6, 6, len=1000)
plot(x, y, ty="p", col='red4', ylim=c(-10, 10), pch=20) ## Note ylim() here ##
abline(h=c(0, 2, -2), col='cyan', lwd=3)

2 个答案:

答案 0 :(得分:2)

我做这样的事情:

library(dplyr)
library(ggplot2)
df1 <- data.frame(x = c(seq(-4, 4, len = 1000), seq(-6, 6, len = 1000)),
                  y = c(rnorm(1000), rcauchy(1000, 0, 1)),
                  method = c(rep("rnorm", 1000), rep("rcauchy", 1000)))
df1 %>% 
  ggplot(aes(x, y)) + geom_point(aes(color = method)) + facet_grid(method ~ ., scales = "free")

结果:

enter image description here

答案 1 :(得分:1)

使用基座R

par(mfrow = c(2, 1))
par(oma = c(4, 4, 0, 0))
par(mar = c(1, 1, 2, 2))
palette(colors())

# Plot #1:   
yy = rnorm(1000)
xx = seq(-4, 4, len=1000)
plot(xx, yy, ty="p", col='green4', xaxt = 'n', xlim=c(-6,6), ylim=c(-4, 4), pch=20, main='Gaussian')  ## Note ylim() here ##
abline(h=c(0, 3, -3 ), col='green1', lwd=3)

# Plot # 2:
y = rcauchy(1000, 0, 1)
x = seq(-6, 6, len=1000)
plot(x, y, ty="p", col='red4', ylim=c(-10, 10), pch=20, main='Cauchy') ## Note ylim() here ##
abline(h=c(0, 2, -2), col='red1', lwd=3)

mtext('x', side = 1, outer = TRUE, line = 2)
mtext('y', side = 2, outer = TRUE, line = 2)

enter image description here 使用lattice

library(lattice)
xyplot(y~x|type,
       data = rbind(data.frame(x=xx, y=yy, type='Gaussian'), 
                    data.frame(x=x, y=y, type='Cauchy')),
       ylim = list(c(-4, 4), c(-10, 10)),
       groups=type,
       col = c("red","blue"),
       pch = 19,
       layout = c(1,2), 
       scales = list(y = list(relation = "free")))

enter image description here

使用ggplot grid

library(grid)
grid.newpage()
grid.draw(rbind(ggplotGrob(ggplot() + aes(x,y) + geom_point(col='red') + ylim(-10,10) + 
                   ggtitle('Cauchy') + theme(axis.title.x = element_blank(), axis.text.x = element_blank())), 
                ggplotGrob(ggplot() + aes(xx,yy) + geom_point(col='blue') + 
                   ggtitle('Gaussian') + xlim(c(-6,6)) + xlab('x') + ylab('y')), size = "last"))

enter image description here