Ggplot2에서 수동 범례를 만드는 방법(예제 포함)


사용자 정의 색상, 레이블, 제목 등을 사용하여 ggplot2의 플롯에 수동 범례를 추가하려는 경우가 종종 있습니다.

다행히 scale_color_manual() 함수를 사용하면 이 작업을 수행하는 것이 간단하며 다음 예제에서는 이를 수행하는 방법을 보여줍니다.

예: ggplot2에서 수동 범례 만들기

다음 코드는 사용자 정의 수동 범례를 사용하여 ggplot2의 플롯에 세 개의 적합 회귀선을 그리는 방법을 보여줍니다.

 library (ggplot2)

#create data frame
df <- data. frame (x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
                 y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))

#create plot with three fitted regression models
ggplot(df, aes(x, y)) +
  geom_point() +
  geom_smooth(se= FALSE , aes(color=' Linear ')) +
  geom_smooth(formula=y~poly(x, 2), se= FALSE , aes(color=' Quadratic ')) +
  geom_smooth(formula=y~poly(x, 3), se= FALSE , aes(color=' Cubic ')) +
  scale_color_manual(name=' Regression Model ',
                     breaks=c(' Linear ', ' Quadratic ', ' Cubic '),
                     values=c(' Cubic '=' pink ', ' Quadratic '=' blue ', ' Linear '=' purple ')) 

scale_color_manual() 함수를 사용하여 범례의 다음 측면을 지정할 수 있었습니다.

  • name : 범례의 제목
  • break : 범례의 레이블
  • : 범례의 색상

theme() 함수를 사용하여 범례 요소의 글꼴 크기를 변경할 수도 있습니다.

 library (ggplot2)

#create data frame
df <- data. frame (x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
                 y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))

#create plot with three fitted regression models
ggplot(df, aes(x, y)) +
  geom_point() +
  geom_smooth(se= FALSE , aes(color=' Linear ')) +
  geom_smooth(formula=y~poly(x, 2), se= FALSE , aes(color=' Quadratic ')) +
  geom_smooth(formula=y~poly(x, 3), se= FALSE , aes(color=' Cubic ')) +
  scale_color_manual(name=' Regression Model ',
                     breaks=c(' Linear ', ' Quadratic ', ' Cubic '),
                     values=c(' Cubic '=' pink ', ' Quadratic '=' blue ', ' Linear '=' purple '))+
 theme(legend. title =element_text(size= 20 ),
       legend. text =element_text(size= 14 ))

제목 및 캡션 레이블의 글꼴 크기가 늘어났습니다.

추가 리소스

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

ggplot2에서 범례 위치를 변경하는 방법
ggplot2에서 범례 크기를 변경하는 방법
ggplot2에서 범례 제목을 변경하는 방법
ggplot2에서 범례 레이블을 변경하는 방법

의견을 추가하다

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