在使用ggplot2初步繪制(ggplot2|詳解八大基本繪圖要素)出需要展示的圖形後,還需要對标題,坐标軸(ggplot2|theme主題設定,詳解繪圖優化-“精雕細琢”)和legend(ggplot2 |legend參數設定,圖形精雕細琢)上的對象進行一系列的設定,包括但不限于名稱更改,顔色,大小,位置和角度的調整。
本文針對性的介紹下如何對标題,坐标軸和legend進行修改和設定,算是之前幾篇推文的一些補充。
一 載入R包 資料
為友善展示,使用ggplot2内置的iris資料集
library(ggplot2)
p <- ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=Species))
p
複制
本文會分别介紹圖中紅色标記部分的修改和設定方法。
二 标題設定
可以通過labs函數添加圖檔标題 以及 subtitle ,caption ;而後通過theme來設定字型的大小,顔色,位置和角度等。
注意theme中對應的更改plot.title ,plot.caption 和 plot.subtitle
p1 <- p + labs(title="學習ggplot2可視化",
subtitle = "熟能生巧",
caption = "生信補給站") +
theme(plot.title=element_text(face="bold.italic", #字型
color="steelblue", #顔色
size=24, #大小
hjust=0.5, #位置
vjust=0.5,
angle=360), # 角度
plot.caption=element_text(face="bold",color="blue",size=20))
p1
複制
三 坐标軸設定
3.1 設定坐标軸
使用labs函數 ,其中x y 即為對應的坐标名字;
p2 <- p1 + labs(x="X軸",y = "這是Y軸",title = "生信補給站")
p2
複制
3.2 設定坐标大小,顔色
根據實際情況設定大小,顔色和傾斜角度可以更清晰的展示結果
p2 + theme(axis.title.x=element_text(vjust=1,
size=20), # X axis title
axis.title.y=element_text(size=10,
color = "blue"), # Y axis title
axis.text.x=element_text(size=10,
angle = 45,
color = "red",
vjust=.5), # X axis text
axis.text.y=element_text(size=10)) # Y axis text
複制
四 圖例設定
legend 可以使用guide函數或者scale函數進行修改,這裡分别進行一下介紹。
4.1 根據guide修改
p3 <- p2 + guides(color=guide_legend(title = "shape change Legend"))
p3
複制
注意這裡使用color=guide_legend ,和aes對應 。
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(shape=Species))+
guides(shape=guide_legend(title = "shape change legend"))
複制
4.2 根據scale修改
p4 <- p2 + scale_colour_discrete(name="scale change Legend")
p4
複制
#綜合一下
ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
geom_point(aes(color=Species,shape=Species)) +
scale_colour_discrete(name="color legend") +
guides(shape=guide_legend(title = "shape legend"))
複制
4.3 更改标簽名稱
4.3.1 使用scale 函數對标簽名稱進行更改
p5 <- p2 + scale_color_discrete(name="scale change \n Legend",
breaks=c("setosa" ,"versicolor","virginica"),
labels=c("Species 1", "Species 2", "Species 3") )
p5
複制
4.3.2 關于legend的其他設定
p5 + theme(legend.title = element_text(size=15,
color = "firebrick"),
legend.text = element_text(size=10),
legend.key=element_rect(fill='blue'))
複制
關于scale函數的一個簡單的“總結”,ggplot2|詳解八大基本繪圖要素也有簡單的介紹。
ggplot2的scale系列函數有很多,命名和用法是有一定規律的。一般使用三個單詞用_連接配接 ,scale_xxx_yyy形式:
其中第二部分的xxx可選為:
colour: 點 線 或者其他圖形的框線顔色
fill: 填充顔色 (注意個colour區分)
linetype :線型, 實線 虛線 點線
shape ,size ,alpha : 分别為形狀, 大小 和 透明度(某些場景有妙用)
其中第三部分的 yyy 可選為:
manual: 手動設定
discrete: 離散資料
continuous :連續資料
gradient: 顔色梯度
grey: 設定灰階值
更多請參考:
https://ggplot2.tidyverse.org/
https://ggplot2-book.org/