Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

multiple plots in R (using par(new=T/F))

I am trying to draw multiple plots in the same graph in R (Rstudio, mac), using:

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)

However, it draws only the third plot.
what am I missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

points

I think it is best to use points for the last two instead of plot.

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

plot

If the OP really wants to use the plot functions, then the following could be useful. (The main error OP made is using the second new=F, but there will be other problems as well since the y-axis labels being on top of each other etc.)

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

While I'm at it, here's version of it too.

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 Data used:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...