Legends(ggplot2)

Problem

ggplot2로 만든 그래프의 범례를 수정할 때 사용한다.

Solution

예제 그래프로 기본 옵션을 보면 아래와 같다. 또한 ggplot에 더해지는 더 많은 manual 들도 확인할 수 있다.

library(ggplot2)
bp <- ggplot(data = PlantGrowth, aes(x = group, y = weight, fill = group)) + 
    geom_boxplot()
bp

plot of chunk unnamed-chunk-1

Removing the legend

guides(fill=FALSE)으로 범례를 제거한 후, 빈공간을 그래프로 대체한다.

밑에 예제와 같이 다른 옵션들을 사용해서도 그래프의 범례를 제거할 수 있다.

# Remove legend for a particular aesthetic (fill)
bp + guides(fill = FALSE)

# It can also be done when specifying the scale
bp + scale_fill_discrete(guide = FALSE)

# This removes all legends
bp + theme(legend.position = "none")

plot of chunk unnamed-chunk-2 plot of chunk unnamed-chunk-2 plot of chunk unnamed-chunk-2

Changing the order of items in the legend

범례의 항목을 trt1, ctr1, trt2로 바꾸는 방법이다.

bp + scale_fill_hue(breaks = c("trt1", "ctrl", "trt2"))

plot of chunk unnamed-chunk-3

색상이 지정된 방법에 따라 scale_fill_manual, scale_colour_hue, scale_colour_manual, scale_shape_discrete, scale_linetype_discrete 등의 다른 척도를 사용할 수 있다. 이러한 scale에 대한 자세한 설명은 아래에 Kinds of scales에서 볼 수 있다.

Reversing the order of items in the legend

범례항목의 순서를 역으로 변환하기 위해 아래와 같은 코드를 실행한다.

# These two methods are equivalent:
bp + guides(fill = guide_legend(reverse = TRUE))
bp + scale_fill_hue(guide = guide_legend(reverse = TRUE))

# You can also modify the scale directly:
bp + scale_fill_hue(breaks = rev(levels(PlantGrowth$group)))

plot of chunk unnamed-chunk-4 plot of chunk unnamed-chunk-4 plot of chunk unnamed-chunk-4

scale_fill_hue대신에, scale_fill_manual, scale_colour_hue, scale_colour_manual, scale_shape_discrete, scale_linetype_discrete와 같은 다른 코드를 사용할 수도 있다.

Hiding the legend title

아래의 예로 범례의 제목을 숨길 수 있다.

# Remove title for fill legend
bp + guides(fill = guide_legend(title = NULL))

# Remove title for all legends
bp + opts(legend.title = theme_blank())

plot of chunk unnamed-chunk-5 plot of chunk unnamed-chunk-5

Modifying the text of legend titles and labels

범례의 제목을 변경하는데는 두가지 방법이 있다. 그 중 한가지는 범례부분의 코드에서 제목과 라벨을 변경해 주는 것이고 나머지 한가지는 factor가 원하는 양식을 가질 수 있도록 data frame을 직접 변경해 주는 것이다. 전자에 대한 자세한 설명은 아래의 With fill and color에서, 후자에 대한 자세한 설명은 Changing the factor in the data frame에서 확인할 수 있다.

Using scales

범례는 채우기색상, 선의 색상, 선의 모양, 형태나 다른 미적인 것들의 guide가 된다.

With fill and color

범례의 변수 group에서 group변수 안의 각 level에 다른 색상을 입히고 싶을 때, 색상에 관해서는 scale_fill_XXX를 사용할 수 있다. 여기서 XXX의 초기값은 hue로써 이미 정해진 색상을 사용하게 된다. 하지만 hue를 manual이나 discrete로 대체하였을 때, 각 level에 수동적으로 색상을 정하는 것이 가능하다.

bp + scale_fill_hue(name = "Experimental\nCondition")
bp + scale_fill_hue(name = "Experimental\nCondition", breaks = c("ctrl", "trt1", 
    "trt2"), labels = c("Control", "Treatment 1", "Treatment 2"))

# Using a manual scale instead of hue
bp + scale_fill_manual(values = c("#999999", "#E69F00", "#56B4E9"), name = "Experimental\nCondition", 
    breaks = c("ctrl", "trt1", "trt2"), labels = c("Control", "Treatment 1", 
        "Treatment 2"))

plot of chunk unnamed-chunk-6 plot of chunk unnamed-chunk-6 plot of chunk unnamed-chunk-6

위의 코드만으로는 x축의 라벨이 바뀌지 않는다. 축의 라벨을 바꾸는 방법은 Axes/)에서 확인할 수 있다.

선 그래프를 사용한다면 scale_fill_xxx대신에 scale_colour_xxx와 scale_shape_xxx도 사용할 수 있다. scale_fill_xxx가 영역을 채우는 색상에 관한 것인데 반해, scale_colour_xxx는 선과 점의 색상에, scale_shape_xxx는 점의 모양에 관한 것이다.

위에서 사용하던 PlantGrowth 데이터 셋은 선 그래프와 함께 잘 작동하지 않기 때문에, 여기서는 선 그래프를 그리기 위한 다른 데이터 셋(df1)을 사용하도록 한다.

# A different data set
df1 <- data.frame(sex = factor(c("Female", "Female", "Male", "Male")), time = factor(c("Lunch", 
    "Dinner", "Lunch", "Dinner"), levels = c("Lunch", "Dinner")), total_bill = c(13.53, 
    16.81, 16.24, 17.42))

# A basic graph
lp <- ggplot(data = df1, aes(x = time, y = total_bill, group = sex, shape = sex)) + 
    geom_line() + geom_point()
lp

# Change the legend
lp + scale_shape_discrete(name = "Payer", breaks = c("Female", "Male"), labels = c("Woman", 
    "Man"))

plot of chunk unnamed-chunk-7 plot of chunk unnamed-chunk-7

선이나 점의 색상과 형태를 모두 변경하고 싶을 때는 필요한 scale을 둘다 입력해야 한다. 그렇지 않으면 색상과 형태에 대해 분리된 2개의 범례가 생기게 된다.

# Specify colour and shape
lp1 <- ggplot(data = df1, aes(x = time, y = total_bill, group = sex, shape = sex, 
    colour = sex)) + geom_line() + geom_point()
lp1

# Here's what happens if you just specify colour
lp1 + scale_colour_hue(name = "Payer", breaks = c("Female", "Male"), labels = c("Woman", 
    "Man"))

# Specify both colour and shape
lp1 + scale_colour_hue(name = "Payer", breaks = c("Female", "Male"), labels = c("Woman", 
    "Man")) + scale_shape_discrete(name = "Payer", breaks = c("Female", "Male"), 
    labels = c("Woman", "Man"))

plot of chunk unnamed-chunk-8 plot of chunk unnamed-chunk-8 plot of chunk unnamed-chunk-8

Kinds of scales

scale의 종류는 매우 많다. 우리는 scale을 scale_xxx_yyy의 형태로 사용한다. 아래의 표가 보통 사용하는 xxx와 yyy의 일부이다.

Changing the factor in the data frame

data frame에서 직접적으로 범례의 제목과 라벨을 바꾸는 또다른 방법이다.

pg <- PlantGrowth  # Copy data into new data frame
# Rename the column and the values in the factor
levels(pg$group)[levels(pg$group) == "ctrl"] <- "Control"
levels(pg$group)[levels(pg$group) == "trt1"] <- "Treatment 1"
levels(pg$group)[levels(pg$group) == "trt2"] <- "Treatment 2"
names(pg)[names(pg) == "group"] <- "Experimental Condition"

# The end product
pg
##    weight Experimental Condition
## 1    4.17                Control
## 2    5.58                Control
## 3    5.18                Control
## 4    6.11                Control
## 5    4.50                Control
## 6    4.61                Control
## 7    5.17                Control
## 8    4.53                Control
## 9    5.33                Control
## 10   5.14                Control
## 11   4.81            Treatment 1
## 12   4.17            Treatment 1
## 13   4.41            Treatment 1
## 14   3.59            Treatment 1
## 15   5.87            Treatment 1
## 16   3.83            Treatment 1
## 17   6.03            Treatment 1
## 18   4.89            Treatment 1
## 19   4.32            Treatment 1
## 20   4.69            Treatment 1
## 21   6.31            Treatment 2
## 22   5.12            Treatment 2
## 23   5.54            Treatment 2
## 24   5.50            Treatment 2
## 25   5.37            Treatment 2
## 26   5.29            Treatment 2
## 27   4.92            Treatment 2
## 28   6.15            Treatment 2
## 29   5.80            Treatment 2
## 30   5.26            Treatment 2
# weight Experimental Condition 4.17 ctrl 5.58 ctrl ...  5.80 trt2 5.26
# trt2

# Make the plot
ggplot(data = pg, aes(x = `Experimental Condition`, y = weight, fill = `Experimental Condition`)) + 
    geom_boxplot()

plot of chunk unnamed-chunk-10

범례의 제목인 “Experimental Condition"은 너무 길기 때문에, 두 줄로 나누어 쓰이는게 더 보기에 좋다. 하지만 열의 이름 안에 줄바꿈문자를 넣어야 해서 실제로 작동되지 않는다. 따라서 scale과 함께 쓰이는 것이 일반적으로 더 좋은 방법이다.

또한 변수이름을 넣을 공간이기 때문에 작은따옴표(') 대신에 back-tick()을 사용한다.

Modifying the appearance of the legend title and labels

# Title appearance
bp + opts(legend.title = theme_text(colour = "blue", size = 16, face = "bold"))

# Label appearance
bp + opts(legend.text = theme_text(colour = "blue", size = 16, face = "bold"))

plot of chunk unnamed-chunk-11 plot of chunk unnamed-chunk-11

Modifying the legend box

범례 상자가 보이지 않는 형태가 초기값이다. 상자를 추가하고 속성을 수정하려면 :

bp + theme(legend.background = theme_rect())
bp + theme(legend.background = theme_rect(fill = "gray90", size = 0.5, linetype = "dotted"))

plot of chunk unnamed-chunk-12 plot of chunk unnamed-chunk-12

Changing the position of the legend

범례의 위치는 그림이 그려진 영역 밖(왼쪽/오른쪽/위/아래)에 가능하다.

bp + opts(legend.position = "top")

plot of chunk unnamed-chunk-13

그림이 그려진 영역 안에 범례를 위치시키는 것도 또한 가능하다. 단지 그림이 그려진 영역이 아니라, 제목과 라벨도 포함한 전체 영역과 연관된 숫자위치 이하에서 가능하다.

# Position legend in graph, where x,y is 0,0 (bottom left) to 1,1 (top
# right)
bp + opts(legend.position = c(0.5, 0.5))

# Set the 'anchoring point' of the legend (bottom-left is 0,0; top-right
# is 1,1) Put bottom-left corner of legend box in bottom-left corner of
# graph
bp + opts(legend.justification = c(0, 0), legend.position = c(0, 0))
# Put bottom-right corner of legend box in bottom-right corner of graph
bp + opts(legend.justification = c(1, 0), legend.position = c(0, 0))

plot of chunk unnamed-chunk-14 plot of chunk unnamed-chunk-14 plot of chunk unnamed-chunk-14

Hiding slashes in the legend

막대 그래프에서 by setting colour=“black"으로 외곽선을 설정하면, 범례에서 이 색상으로 사선이 그어지게 된다. 이 사선을 제거하기 위해 내장된 방법은 없지만, show_guide=FALSE라는 부분을 추가해줌으로써 사선을 제거한 것처럼 보이게 할 수 있다.

# No outline
ggplot(data = PlantGrowth, aes(x = group, fill = group)) + geom_bar()

# Add outline, but slashes appear in legend
ggplot(data = PlantGrowth, aes(x = group, fill = group)) + geom_bar(colour = "black")

# A hack to hide the slashes: first graph the bars with no outline and add
# the legend, then graph the bars again with outline, but with a blank
# legend.
ggplot(data = PlantGrowth, aes(x = group, fill = group)) + geom_bar() + geom_bar(colour = "black", 
    show_guide = FALSE)

plot of chunk unnamed-chunk-15 plot of chunk unnamed-chunk-15 plot of chunk unnamed-chunk-15

Notes

좀 더 많은 정보를 원하시면 (https://github.com/hadley/ggplot2/wiki/Legend-Attributes)


Hankuk University of Foreign Studies. Dept of Statistics. Daewoo Choi Lab. Yeeseul Han.
한국외국어대학교 통계학과 최대우 연구실 한이슬
e-mail : han.lolove17@gmail.com