首頁 > 軟體

R語言ggplot2設定圖例(legend)的操作大全

2022-07-21 14:04:39

本文在 http://www.cookbook-r.com/Graphs/Scatterplots_(ggplot2)/ 的基礎上加入了自己的理解

圖例用來解釋圖中的各種含義,比如顏色,形狀,大小等等, 在ggplot2中aes中的引數(x, y 除外)基本都會生成圖例來解釋圖形, 比如 fill, colour, linetype, shape.

基本箱線圖(帶有圖例)

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

移除圖例

Use guides(fill=FALSE), replacing fill with the desired aesthetic. 使用 guides(fill=FALSE) 移除由ase中 匹配的fill生成的圖例, 也可以使用theme You can also remove all the legends in a graph, using theme.

bp + guides(fill=FALSE)

# 也可以這也
bp + scale_fill_discrete(guide=FALSE)

# 移除所有圖例
bp + theme(legend.position="none")

修改圖例的內容

改變圖例的順序為 trt1, ctrl, trt2:

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

 根據不同的分類,可以使用 scale_fill_manualscale_colour_hue,scale_colour_manualscale_shape_discretescale_linetype_discrete 等等.

顛倒圖例的順序

# 多種方法
bp + guides(fill = guide_legend(reverse=TRUE))

# 也可以
bp + scale_fill_discrete(guide = guide_legend(reverse=TRUE))

# 還可以這也
bp + scale_fill_discrete(breaks = rev(levels(PlantGrowth$group)))

隱藏圖例標題

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

# Remove title for all legends
bp + theme(legend.title=element_blank())

修改圖例中的標籤

兩種方法一種是直接修改標籤, 另一種是修改data.frame

Using scales

圖例可以根據 fill, colour, linetype, shape 等繪製, 我們以 fill 為例, scale_fill_xxxxxx 表示處理資料的一種方法, 可以是 hue(對顏色的定量操作), continuous(連續型資料處理), discete(離散型資料處理)等等.

# 設定圖例名稱
bp + scale_fill_discrete(name="ExperimentalnCondition")

# 設定圖例的名稱, 重新定義新的標籤名稱
bp + scale_fill_discrete(name="ExperimentalnCondition",
                         breaks=c("ctrl", "trt1", "trt2"),
                         labels=c("Control", "Treatment 1", "Treatment 2"))

# 自定義fill的顏色
bp + scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"), 
                       name="ExperimentalnCondition",
                       breaks=c("ctrl", "trt1", "trt2"),
                       labels=c("Control", "Treatment 1", "Treatment 2"))

注意這裡並不能修改 x軸 的標籤,如果需要改變x軸的標籤,可以參照http://blog.csdn.net/tanzuozhev/article/details/51107583

# 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

# 修改圖例
lp + scale_shape_discrete(name  ="Payer",
                          breaks=c("Female", "Male"),
                          labels=c("Woman", "Man"))

 If you use both colour and shape, they both need to be given scale specifications. Otherwise there will be two two separate legends. 如果同時使用 colorshape,那麼必須都進行scale_xx_xxx的定義,否則colorshape的圖例就會合併到一起, 如果 scale_xx_xxx 中的name相同,那麼他們也會合併到一起.

# 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_discrete(name  ="Payer",
                            breaks=c("Female", "Male"),
                            labels=c("Woman", "Man"))

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

 ### scale的種類

scale_xxx_yyy:

xxx 的分類 colour: 點 線 或者其他圖形的框線顏色 fill: 填充顏色 linetype :線型, 實線 虛線 點線 shape: 點的性狀,超級多,可以自己搜尋一下 size: 點的大小 alpha: 透明度

yyy 的分離 hue: 設定色調範圍(h)、飽和度(c)和亮度(l)獲取顏色 manual: 手動設定 gradient: 顏色梯度 grey: 設定灰度值discrete: 離散資料 (e.g., colors, point shapes, line types, point sizes) continuous 連續行資料 (e.g., alpha, colors, point sizes)

修改data.frame的factor

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"
 
# View a few rows from the end product
head(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
# Make the plot 
ggplot(data=pg, aes(x=`Experimental Condition`, y=weight, fill=`Experimental Condition`)) +
    geom_boxplot()

修改標題和標籤的顯示

# 標題
bp + theme(legend.title = element_text(colour="blue", size=16, face="bold"))

# 標籤
bp + theme(legend.text = element_text(colour="blue", size = 16, face = "bold"))

修改圖例的框架

bp + theme(legend.background = element_rect())

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

設定圖例的位置

圖例的位置(left/right/top/bottom):

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

 也可以根據座標來設定圖例的位置, 左下角為 (0,0), 右上角為(1,1)

# Position legend in graph, where x,y is 0,0 (bottom left) to 1,1 (top right)
bp + theme(legend.position=c(.5, .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 + theme(legend.justification=c(0,0), # 這個引數設定很關鍵
           legend.position=c(0,0))

# Put bottom-right corner of legend box in bottom-right corner of graph
bp + theme(legend.justification=c(1,0), legend.position=c(1,0))

隱藏斜線

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

# 如果設定了顏色, 那麼圖例中就會出現 黑色斜線
ggplot(data=PlantGrowth, aes(x=group, fill=group)) +
    geom_bar(colour="black")

# 黑魔法: 可以先設定geom_bar, 然後再來一個沒有 圖例 的 geom_bar
ggplot(data=PlantGrowth, aes(x=group, fill=group)) +
    geom_bar() +
    geom_bar(colour="black", show_guide=FALSE)

總結 

到此這篇關於R語言ggplot2設定圖例(legend)的文章就介紹到這了,更多相關R語言ggplot2圖例內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com