不知道大家有沒有印象谊却,其實(shí)關(guān)于調(diào)整ggplot2圖形背景,圖例哑芹,XY軸范圍及標(biāo)簽等的問題在我們往期公眾號(hào)有推文介紹過炎辨,但是以前給大家介紹的是利用ggThemeAssist 包經(jīng)過鼠標(biāo)調(diào)整,然后一鍵生成代碼聪姿,我個(gè)人覺得這個(gè)包非常方便實(shí)用碴萧,感興趣的朋友可以看一下:ggThemeAssist | 鼠標(biāo)調(diào)整ggplot2主題并自動(dòng)生成代碼乙嘀,優(yōu)秀!
今天我們脫離ggThemeAssist包破喻,給大家介紹直接用代碼如何調(diào)整ggplot2圖形背景虎谢,圖例,XY軸范圍及標(biāo)簽等曹质。當(dāng)然了婴噩,大家可以結(jié)合ggThemeAssist包一起學(xué)習(xí),加深記憶咆繁。
一.旋轉(zhuǎn)XY軸標(biāo)簽
library(ggplot2)
p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len,fill=factor(dose))) +
geom_boxplot()
p
1.改變x軸標(biāo)簽與x軸的角度與距離
p + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
2.將x軸標(biāo)簽加粗讳推,字體顏色變紅顶籽,大小為12號(hào)玩般,角度與x軸成45度(y軸標(biāo)簽類似)
p + theme(axis.text.x = element_text(face = "bold", color = "red",
size = 12, angle = 45),
axis.text.y = element_text(face = "bold", color = "blue",
size = 12, angle = 45))
3.刪除x,y軸標(biāo)簽
p + theme(axis.text.x = element_blank(), axis.text.y = element_blank())
4.刪除x礼饱,y軸標(biāo)簽和刻度
p + theme(axis.text.x = element_blank(), axis.text.y = element_blank(),
axis.ticks = element_blank())
二.設(shè)置x軸范圍
1.使用xlim()設(shè)置X軸范圍
p+xlim(0,5)#這里因?yàn)閤軸是分組變量坏为,所以會(huì)出錯(cuò),如果x軸為連續(xù)變量就不會(huì)出錯(cuò)
2.使用ylim()設(shè)置y軸范圍
p + ylim(0, 45)
3.使用coord_cartesian()設(shè)置X,Y軸范圍
p+ coord_cartesian(xlim =c(0, 3), ylim = c(0, 50))
三.改變圖例位置
1.圖例在圖外面
ToothGrowth$dose<-factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
geom_boxplot()
p
2.圖例在圖里面
p+ theme(legend.position = c(.9, .9))
3.刪除圖例
p+ theme(legend.position = "none")
4.改變圖例背景色
p + theme(legend.background = element_rect(fill="pink", size=0.5, linetype="solid"))
四.改變背景顏色
1.背景色中添加綠色輔助線
p + theme(panel.background = element_rect(fill = 'white', color = 'blue'),
panel.grid.major = element_line(color = 'green', linetype = 'dotted'),
panel.grid.minor = element_line(color = 'green', size = 2))
2.白色背景灰色網(wǎng)格線
p + theme_bw()
3.沒有外框
p + theme_minimal()
4.只有xy軸,沒有網(wǎng)格線
p + theme_classic()
5.黑色網(wǎng)格線
p + theme_linedraw()
6.淺灰色網(wǎng)格線和外框
p + theme_light()
7.無背景
p + theme_void()
8.暗背景
p + theme_dark() #暗背景
今天的學(xué)習(xí)到這镊绪,歡迎大家關(guān)注我們的公眾號(hào)匀伏!
參考鏈接:https://www.r-bloggers.com/2021/09/how-to-change-legend-position-in-ggplot2-2/;https://www.r-bloggers.com/2021/09/how-to-set-axis-limits-in-ggplot2/蝴韭;https://www.r-bloggers.com/2021/09/how-to-change-background-color-in-ggplot2/够颠; https://www.r-bloggers.com/2021/09/how-to-rotate-axis-labels-in-ggplot2/