R中的多个图(使用par(new = T / F))

时间:2018-04-17 00:11:09

标签: r plot figure

我试图在R(Rstudio,mac)的同一个图中绘制多个图,使用:

plot(
  X,
  Y1,
  pch = 0,
  ylim = c(min_v, max_v),
  col = "red"
)
par(new = T)
plot(
  X,
  Y2,
  pch = 1,
  ylim = c(min_v, max_v),
  col = "blue"
)
par(new = F)

plot(
  X,
  Y3,
  pch = 2,
  ylim = c(min_v, max_v),
  col = "green"
)
par(new = F)

然而,它只绘制了第三个情节 我错过了什么?

1 个答案:

答案 0 :(得分:2)

我认为最好使用points代替情节。

min_v <- min(Y1, Y2, Y3)
max_v <- max(Y1, Y2, Y3)
xr <- range(X)

plot(X, Y1, pch = 21, ylim = c(min_v, max_v),
  xlim = xr, bg = "red", , 
  ylab = expression(paste(Y[i],', i = {1, 2, 3}')), xlab ="X")
points(X, Y2, pch = 22, bg = "blue")
points(X, Y3, pch = 23, bg = "green")

enter image description here

如果OP确实想要使用plot函数,那么以下内容可能会有用。 (OP的主要错误是使用第二个new=F,但是由于y轴标签彼此叠加等,因此还会出现其他问题。)

plot(
  X, Y1, pch = 21, ylim = c(min_v, max_v),
  xlim = xr,
  bg = "red",
  ylab = "", xlab ="",
)
par(new = T)
plot(
  X, Y2, pch = 22, ylim = c(min_v, max_v),
  xlim = xr,
  bg = "blue",
  ylab = "", xlab ="",
)

par(new = T)
plot(
  X, Y3, pch = 23, ylim = c(min_v, max_v),
  xlim = xr,
  bg = "green",
  ylab = expression(paste(Y[i],', i = {1, 2, 3}')),
  xlab ="X",
)
par(new = F)

enter image description here

GGPLOT2

虽然我在这里,但也有版本。

library(ggplot2)
df <- data.frame(X=X, Y1=Y1, Y2=Y2, Y3=Y3)
p1 <- ggplot(df, aes(x = X, y=Y1)) + geom_point(color = "red")
p1 <- p1 + geom_point(color = "blue", aes(y=Y2))
p1 <- p1 + geom_point(color = "black", aes(y=Y3)) 
p1 + xlab("X") + ylab("Y")
p1

enter image description here 使用的数据:

set.seed(1984)
X <- rnorm(10)
Y1 <- rnorm(10)
Y2 <- rnorm(10)
Y3 <- rnorm(10)