Ggplot2를 사용하여 플롯에 수직선을 추가하는 방법
다음 구문을 사용하는 geom_vline() 함수를 사용하면 ggplot2 플롯에 수직선을 빠르게 추가할 수 있습니다.
geom_vline(xintercept, 선종류, 색상, 크기)
금:
- xintercept: x 교차점에 선을 추가할 위치입니다. 하나 이상의 값일 수 있습니다.
- 선종류: 선 스타일. 기본값은 “solid”이지만 “twodash”, “longdash”, “dotted”, “dotdash”, “dash” 또는 “blank”를 지정할 수 있습니다.
- 색상: 선의 색상입니다.
- 크기: 선의 너비입니다.
다음 예에서는 이 기능을 실제로 사용하는 방법을 보여줍니다.
경로에 단일 수직선 추가
다음 코드는 플롯에 단일 수직선을 추가하는 방법을 보여줍니다.
library (ggplot2) #create data frame df <- data.frame(x=c(1, 3, 3, 4, 5, 5, 6, 9, 12, 15), y=c(13, 14, 14, 12, 17, 21, 22, 28, 30, 31)) #create scatterplot with vertical line at x=10 ggplot(df, aes (x=x, y=y)) + geom_point() + geom_vline(xintercept= 10 )
경로에 여러 개의 수직선 추가
다음 코드는 경로에 여러 개의 수직선을 추가하는 방법을 보여줍니다.
library (ggplot2) #create data frame df <- data.frame(x=c(1, 3, 3, 4, 5, 5, 6, 9, 12, 15), y=c(13, 14, 14, 12, 17, 21, 22, 28, 30, 31)) #create scatterplot with vertical line at x=6, 10, and 11 ggplot(df, aes (x=x, y=y)) + geom_point() + geom_vline(xintercept=c( 6, 10, 11 ))
수직선 사용자 정의
다음 코드는 경로의 수직선을 사용자 정의하는 방법을 보여줍니다.
library (ggplot2) #create data frame df <- data.frame(x=c(1, 3, 3, 4, 5, 5, 6, 9, 12, 15), y=c(13, 14, 14, 12, 17, 21, 22, 28, 30, 31)) #create scatterplot with customized vertical line ggplot(df, aes (x=x, y=y)) + geom_point() + geom_vline(xintercept= 5 , linetype=' dashed ', color=' blue ', size =2 )
차트에 여러 개의 수직선이 있는 경우 각 선에 고유한 색상을 지정할 수 있습니다.
library (ggplot2) #create data frame df <- data.frame(x=c(1, 3, 3, 4, 5, 5, 6, 9, 12, 15), y=c(13, 14, 14, 12, 17, 21, 22, 28, 30, 31)) #create scatterplot with customized vertical lines ggplot(df, aes (x=x, y=y)) + geom_point() + geom_vline(xintercept=c( 5,7 ) , linetype=' dashed ', color=c(' blue ', ' red '))
추가 리소스
다음 튜토리얼에서는 ggplot2에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
ggplot2에서 선형 회귀선을 그리는 방법
ggplot2에서 축 제한을 설정하는 방법
ggplot2에서 병렬 플롯을 만드는 방법