R에서 동일한 그래프에 여러 플롯을 그리는 방법(예제 3개)
다음 방법을 사용하여 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
by(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
by(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 ')

예 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
by(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에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.