여러 줄로 ggplot2에서 범례를 만드는 방법


다음 구문을 사용하여 ggplot2에서 여러 줄로 범례를 만들 수 있습니다.

 ggplot(df, aes(x=x_var, y=y_var, color=group_var)) +
geom_point() +
  guides(color=guide_legend(nrow= 2 , byrow= TRUE )) 

nrow 인수의 값은 범례에 사용할 줄 수를 지정합니다.

다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.

예: ggplot2에서 여러 줄로 범례 만들기

다양한 농구 선수에 대한 정보를 포함하는 다음과 같은 데이터 프레임이 R에 있다고 가정합니다.

 #create data frame
df <- data. frame (team=c('Mavs', 'Heat', 'Nets', 'Lakers', 'Suns', 'Cavs'),
                 points=c(24, 20, 34, 39, 28, 29),
                 assists=c(5, 7, 6, 9, 12, 13))

#view data frame
df

    team points assists
1 Mavs 24 5
2 Heat 20 7
3 Nets 34 6
4 Lakers 39 9
5 Suns 28 12
6 Cavs 29 13

범례에 사용할 줄 수를 지정하지 않고 ggplot2에서 산점도를 생성하면 ggplot2는 기본적으로 각 줄에 레이블을 배치합니다.

 library (ggplot2)

#create default scatterplot
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size= 3 )

여러 줄로 된 범례를 만들려면 nrow 인수와 함께 guides() 함수를 사용해야 합니다.

 library (ggplot2)

#create scatterplot with two rows in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size= 3 ) +
  guides(color=guide_legend(nrow= 2 , byrow= TRUE )) 

이제 범례에 두 줄이 있습니다.

범례의 위치도 변경하려면 legend.position 인수와 함께 theme() 함수를 사용할 수 있습니다.

 library (ggplot2)

#create scatterplot with two rows in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size= 3 ) +
  theme(legend. position = ' bottom ') +
  guides(color=guide_legend(nrow= 2 , byrow= TRUE )) 

이제 범례는 플롯의 맨 아래에 위치하며 두 줄로 구성됩니다.

추가 리소스

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

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

의견을 추가하다

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