Ggplot2에서 범례 항목 사이의 간격을 변경하는 방법


다음 방법을 사용하여 ggplot2에서 범례 요소 사이의 간격을 변경할 수 있습니다.

방법 1: 가로 간격 변경

 p+
  theme(legend. spacing . x = unit(1, ' cm '))

방법 2: 수직 간격 변경

 p+
  theme(legend. spacing . y = unit(1, ' cm ')) +
  guides(fill = guide_legend(byrow = TRUE ))

다음 예에서는 다음 데이터 프레임을 사용하여 실제로 각 메서드를 사용하는 방법을 보여줍니다.

 #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

예 1: 범례 요소 사이의 가로 간격 변경

다음 코드는 기본 간격이 있는 가로 범례를 사용하여 ggplot2에서 산점도를 만드는 방법을 보여줍니다.

 library (ggplot2)

#create scatterplot with default spacing in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size= 3 ) +
  theme(legend. position = ' bottom ')

범례 요소 사이의 가로 간격을 늘리려면 legend.spacing.x 인수를 사용할 수 있습니다.

 library (ggplot2)

#create scatterplot with increased horizontal spacing in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size= 3 ) +
  theme(legend. position = ' bottom ',
        legend. spacing . x = unit(1, ' cm ')) 

ggplot2 범례 요소 사이의 수평 간격을 늘렸습니다.

범례 요소 사이의 가로 간격이 늘어났습니다.

Unit() 함수에 사용하는 값이 클수록 요소 사이의 간격이 커집니다.

예 2: 캡션 요소 사이의 세로 간격 변경

다음 코드는 기본 간격이 있는 수직 범례를 사용하여 ggplot2에서 산점도를 생성하는 방법을 보여줍니다.

 library (ggplot2)

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

범례 요소 사이의 수직 간격을 늘리려면 legend.spacing.y 인수를 사용할 수 있습니다.

 library (ggplot2)

#create scatterplot with increased vertical spacing in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
  geom_point(size= 3 ) +
  theme(legend. spacing . y = unit(1, ' cm ')) +
  guides(fill = guide_legend(byrow = TRUE )) 

ggplot2는 범례 요소 사이의 수직 간격을 늘립니다.

범례 요소 사이의 수직 간격이 늘어났습니다.

Unit() 함수에 사용하는 값이 클수록 요소 사이의 간격이 커집니다.

참고 : byrow = TRUE 인수를 사용하는 마지막 줄을 포함해야 합니다. 그렇지 않으면 범례 요소의 간격이 예상대로 지정되지 않습니다.

추가 리소스

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

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

의견을 추가하다

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