Ggplot2 범례에서 항목 순서를 변경하는 방법


다음 구문을 사용하여 ggplot2 범례의 요소 순서를 변경할 수 있습니다.

 scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)

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

예: ggplot2 범례의 요소 순서 변경

단일 플롯에 여러 상자 그림을 표시하는 ggplot2에서 다음 플롯을 생성한다고 가정합니다.

 library (ggplot2)

#create data frame
df <- data. frame (team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'VS'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes (x=team, y=points, fill=team)) +
  geom_boxplot() 

범례의 요소 순서를 변경하려면 다음과 같이 scale_fill_discrete() 함수를 사용할 수 있습니다.

 library (ggplot2)

#create data frame
df <- data. frame (team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'VS'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes (x=team, y=points, fill=team)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A')) 

범례에 특정 순서의 요소가 있는 ggplot2 boxplot

요소의 순서가 A, B, C에서 B, C, A로 변경되었습니다.

또한 labels 인수를 사용하여 범례 요소에 사용되는 특정 레이블을 수정할 수도 있습니다.

 library (ggplot2)

#create data frame
df <- data. frame (team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'VS'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes (x=team, y=points, fill=team)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A'),
                      labels=c('B Team', 'C Team', 'A Team')) 

범례 레이블이 변경되었습니다.

추가 리소스

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

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

의견을 추가하다

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