关于调整ggplot2图形背景,图例,XY轴范围及标签等的问题
2021-10-09 本文已影响0人
R语言与SPSS学习笔记
不知道大家有没有印象,其实关于调整ggplot2图形背景,图例,XY轴范围及标签等的问题在我们往期公众号有推文介绍过,但是以前给大家介绍的是利用ggThemeAssist 包经过鼠标调整,然后一键生成代码,我个人觉得这个包非常方便实用,感兴趣的朋友可以看一下:ggThemeAssist | 鼠标调整ggplot2主题并自动生成代码,优秀!
今天我们脱离ggThemeAssist包,给大家介绍直接用代码如何调整ggplot2图形背景,图例,XY轴范围及标签等。当然了,大家可以结合ggThemeAssist包一起学习,加深记忆。
一.旋转XY轴标签
library(ggplot2)
p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len,fill=factor(dose))) +
geom_boxplot()
p

1.改变x轴标签与x轴的角度与距离
p + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))

2.将x轴标签加粗,字体颜色变红,大小为12号,角度与x轴成45度(y轴标签类似)
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轴标签
p + theme(axis.text.x = element_blank(), axis.text.y = element_blank())

4.删除x,y轴标签和刻度
p + theme(axis.text.x = element_blank(), axis.text.y = element_blank(),
axis.ticks = element_blank())

二.设置x轴范围
1.使用xlim()设置X轴范围
p+xlim(0,5)#这里因为x轴是分组变量,所以会出错,如果x轴为连续变量就不会出错
2.使用ylim()设置y轴范围
p + ylim(0, 45)

3.使用coord_cartesian()设置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.白色背景灰色网格线
p + theme_bw()

3.没有外框
p + theme_minimal()

4.只有xy轴,没有网格线
p + theme_classic()

5.黑色网格线
p + theme_linedraw()

6.浅灰色网格线和外框
p + theme_light()
7.无背景
p + theme_void()
8.暗背景
p + theme_dark() #暗背景

今天的学习到这,欢迎大家关注我们的公众号!
参考链接: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/