R의 단일 차트에 여러 줄(데이터 시리즈)을 그리는 방법
이 튜토리얼에서는 R의 단일 차트에 여러 줄(예: 데이터 시리즈)을 그리는 방법을 설명합니다.
그래프에 여러 선을 그리려면 기본 R을 사용하거나 ggplot2와 같은 보다 정교한 패키지를 설치할 수 있습니다.
BaseR 사용
다음은 Base R을 사용하여 단일 그래프에 여러 선을 그리는 방법에 대한 두 가지 예입니다.
예제 1: Matplot 사용
대규모 형식의 데이터 세트가 있는 경우 그래프에 여러 선을 그리는 쉬운 방법은 matplot을 사용하는 것입니다.
#Create a fake dataset with 3 columns (ncol=3) composed of randomly generated #numbers from a uniform distribution with minimum = 1 and maximum = 10 data <- matrix(runif(30,1,10), ncol=3) data [,1] [,2] [,3] #[1,] 5.371653 3.490919 3.953603 #[2,] 9.551883 2.681054 9.506765 #[3,] 3.525686 1.027758 8.059011 #[4,] 9.923080 1.337935 1.112361 #[5,] 7.273972 7.627546 1.174340 #[6,] 8.859109 3.778144 9.384526 #[7,] 9.614542 3.866029 7.301729 #[8,] 9.288085 5.804041 8.347907 #[9,] 1.696849 4.650687 7.220209 #[10,] 5.820941 4.799682 5.243663 #plot the three columns of the dataset as three lines and add a legend in #the top right corner of the chart matplot(data, type = "b",pch=1,col = 1:3) legend("topright", legend = 1:3, col=1:3, pch=1)
이 코드는 다음 그래프를 생성합니다.
예 2: 점과 선 사용
여러 선을 그리는 또 다른 방법은 내장 R 함수 points() 및 line()을 사용하여 한 번에 하나씩 그리는 것입니다. 아래 코드는 이 접근 방식의 예를 보여줍니다.
#generate an x-axis along with three data series x <- c(1,2,3,4,5,6) y1 <- c(2,4,7,9,12,19) y2 <- c(1,5,9,8,9,13) y3 <- c(3,6,12,14,17,15) #plot the first data series using plot() plot(x, y1, type="o", col="blue", pch="o", ylab="y", lty=1) #add second data series to the same chart using points() and lines() points(x, y2, col="red", pch="*") lines(x, y2, col="red",lty=2) #add third data series to the same chart using points() and lines() points(x, y3, col="dark red",pch="+") lines(x, y3, col="dark red", lty=3) #add a legend in top left corner of chart at (x, y) coordinates = (1, 19) legend(1,19,legend=c("y1","y2","y3"), col=c("blue","red","black"), pch=c("o","*","+"),lty=c(1,2,3), ncol=1)
이 코드는 다음 그래프를 생성합니다.
ggplot2 사용
다음은 ggplot2를 사용하여 단일 그래프에 여러 선을 그리는 방법의 예입니다.
#install (if not already installed) and load ggplot2 package if(!require(ggplot2)){install.packages(' ggplot2 ')} #generate fake dataset with three columns 'x', 'value', and 'variable' data <- data. frame (x=rep(1:5, 3), value=sample(1:100, 15), variable=rep(paste0(' series ', 1:3), each=5)) #view dataset head(data) x value variable 1 1 93 series1 2 2 64 series1 3 3 36 series1 4 4 17 series1 5 5 95 series1 6 1 80 series2 #plot all three series on the same chart using geom_line() ggplot(data = data, aes(x=x, y=value)) + geom_line(aes(color=variable))
그러면 다음 그래프가 생성됩니다.
추가 리소스
다음 튜토리얼에서는 ggplot2에서 다른 일반적인 플로팅 작업을 수행하는 방법을 설명합니다.
ggplot2에서 범례 위치를 변경하는 방법
ggplot2에서 범례 제목을 변경하는 방법
ggplot2에서 여백을 변경하는 방법