Geom_abline을 사용하여 ggplot2에 직선을 추가하는 방법


geom_abline() 함수 및 기타 유사한 geom 함수를 사용하여 ggplot2의 플롯에 직선을 추가할 수 있습니다.

이러한 기능을 사용하는 가장 일반적인 방법은 다음과 같습니다.

방법 1: geom_abline()을 사용하여 경사와 교차점이 있는 선 추가

 ggplot(df, aes(x, y)) +
  geom_point() +
  geom_abline(slope= 3 , intercept= 15 )

방법 2: geom_vline()을 사용하여 수직선 추가

 ggplot(df, aes(x=xvar, y=yvar)) +
    geom_point() +
    geom_vline(xintercept= 5 )

방법 3: geom_hline()을 사용하여 수평선 추가

 ggplot(df, aes(x=xvar, y=yvar)) +
    geom_point() +
    geom_hline(yintercept= 25 )

방법 4: geom_smooth()를 사용하여 회귀선 추가

 ggplot(df, aes(x=xvar, y=yvar)) +
    geom_point() +
    geom_smooth(method=' lm ')

다음 예는 R의 다음 데이터 프레임에서 실제로 이러한 각 방법을 사용하는 방법을 보여줍니다.

 #create data frame
df <- data. frame (x=c(1, 2, 3, 3, 5, 7, 9),
                 y=c(8, 14, 18, 25, 29, 33, 25))

#view data frame
df

  xy
1 1 8
2 2 14
3 3 18
4 3 25
5 5 29
6 7 33
7 9 25

예 1: geom_abline()을 사용하여 경사와 교차점이 있는 선 추가

다음 코드는 geom_abline()을 사용하여 기울기가 3이고 y절편이 15인 산점도에 직선을 추가하는 방법을 보여줍니다.

 library (ggplot2)

#create scatterplot and add straight line with specific slope and intercept
ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_abline(slope= 3 , intercept= 15 ) 

ggplot2의 geom_abline

예 2: geom_vline()을 사용하여 수직선 추가

다음 코드는 geom_vline()을 사용하여 x=5에서 산점도에 수직선을 추가하는 방법을 보여줍니다.

 library (ggplot2)

#create scatterplot and add vertical line at x=5
ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_vline(xintercept= 5 ) 

R 예제의 geom_vline 함수

예제 3: geom_hline()을 사용하여 수평선 추가

다음 코드는 geom_hline()을 사용하여 y=25에서 산점도에 수평선을 추가하는 방법을 보여줍니다.

 library (ggplot2)

#create scatterplot and add horizontal line at y=25
ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_hline(yintercept= 25 ) 

ggplot의 geom_hline 예

예 4: geom_smooth()를 사용하여 회귀선 추가

다음 코드는 geom_smooth()를 사용하여 적합 회귀선을 산점도에 추가하는 방법을 보여줍니다.

 library (ggplot2)

#create scatterplot and add fitted regression line
ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth(method=' lm ', se= FALSE ) 

ggplot2 예제에 회귀선을 추가하는 geom_smooth

참고 : se=FALSE 인수는 ggplot2에게 표준 오류 추정에 대해 음영선을 표시하지 않도록 지시합니다.

추가 리소스

다음 튜토리얼에서는 ggplot2에서 일반적으로 사용되는 다른 작업을 수행하는 방법을 설명합니다.

ggplot2에서 선 두께를 조정하는 방법
ggplot2에서 축 제한을 설정하는 방법
ggplot2에서 눈금선을 제거하는 방법
ggplot2에서 배경색을 변경하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다