如何在R语言中在同一个图形上绘制多个图形(3个例子)

733 阅读2分钟

你可以使用以下方法在R语言中的同一个图形上绘制多幅图。

方法1:在同一图形上绘制多条线

#plot first line
plot(x, y1, type='l')

#add second line to plot
lines(x, y2)

方法2:创建并排的多幅图

#define plotting area as one row and two columns
par(mfrow = c(1, 2))

#create first plot
plot(x, y1, type='l')

#create second plot
plot(x, y2, type='l')

方法3:创建垂直堆叠的多幅图

#define plotting area as two rows and one column
par(mfrow = c(2, 1))
  
#create first plot
plot(x, y1, type='l')

#create second plot
plot(x, y2, type='l')

下面的例子展示了如何在实践中使用每种方法。

例1:在同一个图形上绘制多条直线

下面的代码显示了如何在R语言中在同一个图形上绘制两条线。

#define data to plot
x <- 1:10
y1 <- c(2, 4, 4, 5, 7, 6, 5, 8, 12, 19)
y2 <- c(2, 2, 3, 4, 4, 6, 5, 9, 10, 13)

#plot first line
plot(x, y1, type='l', col='red', xlab='x', ylab='y')

#add second line to plot
lines(x, y2, col='blue')

R plot multiple plots in same graph

例2:并排创建多条曲线

下面的代码展示了如何使用**par()**参数来并排绘制多幅图。

#define data to plot
x <- 1:10
y1 <- c(2, 4, 4, 5, 7, 6, 5, 8, 12, 19)
y2 <- c(2, 2, 3, 4, 4, 6, 5, 9, 10, 13)

#define plotting area as one row and two columns
par(mfrow = c(1, 2))

#create first line plot
plot(x, y1, type='l', col='red')

#create second line plot
plot(x, y2, type='l', col='blue', ylim=c(min(y1), max(y1)))

请注意,我们在第二幅图中使用了ylim()参数,以确保两幅图的y轴界限相同。

例子 3: 创建垂直堆叠的多幅图

下面的代码显示了如何使用**par()**参数来绘制垂直堆叠的多幅图。

#define data to plot
x <- 1:10
y1 <- c(2, 4, 4, 5, 7, 6, 5, 8, 12, 19)
y2 <- c(2, 2, 3, 4, 4, 6, 5, 9, 10, 13)

#define plotting area as two rows and one column
par(mfrow = c(2, 1), mar = c(2, 4, 4, 2))
#create first line plot
plot(x, y1, type='l', col='red')

#create second line plot
plot(x, y2, type='l', col='blue', ylim=c(min(y1), max(y1)))

注意,我们用mar参数来指定绘图区域的(下、左、上、右)边距。

**注意:**默认情况是mar = c(5.1, 4.1, 4.1, 2.1)

其他资源

下面的教程解释了如何在R中执行其他常见任务。

如何在R中绘制多列图形
如何在R中在图形外绘制图例
如何在R中创建对数图

The postHow to Plot Multiple Plots on Same Graph in R (3 Examples)appeared first onStatology.