ggplot2基础(4)——主题
ggplot2基础(1)
ggplot2基础(2)——坐标轴
ggplot2基础(3)——注释
ggplot2基础(4)——主题
ggplot2基础(5)——配色与图例
在R自带的绘图中,主要使用par()函数进行设置。在ggplot2中则主要通过theme()进行设置。一般而言,ggplot的主题包含以下几类元素:
- 文本类型
- 线条类型
- 矩形框类型
在设置时,分别使用element_text()、element_line()、element_rect()函数进行设置
参考《R数据可视化手册》
1 文本外观
与文本相关的参数主要包括:
-
text所有文本元素 -
axis.title双轴标签的外观 -
axis.title.xx轴标签的外观 -
axis.title.yy轴标签的外观 -
axis.ticks双轴刻度标签的外观 -
axis.ticks.xx轴刻度标签的外观 -
axis.ticks.yy轴刻度标签的外观 -
legend.title图例标签的外观 -
legend.text图例项文本的外观 -
plot.title图形整体标签的外观 -
strip.text双向分面标签的外观 -
strip.text.x横向分面标签的外观 -
strip.text.y纵向分面标签的外观 -
legend.text图例项文本的外观 -
lengend.title图例标题的外观
在设置上述属性时,需要通过element_text()函数,常用的文本属性包括:
-
familyHelvetica(无衬线)、Times(衬线)、Courier(等宽) -
faceplain(普通)、bold(粗体)、italic(斜体)、bold.italic(粗斜体) -
colour字体颜色 -
size字体大小 -
hjust横向对其:0表示左对齐,0.5表示居中,1表示右对齐 -
vjust纵向对齐:0表示底部对齐,0.5表示居中,1表示顶部对齐 -
angle旋转角度 -
lineheight行间距倍数
library(ggplot2)
p <- ggplot(economics,aes(pop,unemploy)) +
geom_point()
windowsFonts(myFont = windowsFont("微软雅黑"))
p +
labs(x="人口",y="失业率",title="经济调查报告")+
theme(
title=element_text(family="myFont",size=12,color="red",
face="italic",hjust=0.2,lineheight=0.2),
axis.text.x=element_text(angle=30, hjust=1)
)

文本对象的主题设置
2 线的外观
在ggplot中,所有线类型的元素的外观也都可以通过theme()函数进行设置,可以使用的参数包括:
-
line所有的线条 -
axis.line坐标轴线 -
panel.grid.major主网格线 -
panel.grid.major.x纵向主网格线 -
panel.grid.major.y横向主网格线 -
panel.grid.minor次网格线 -
panel.grid.minor.x纵向次网格线 -
panel.grid.minor.y横向次网格线 -
axis.ticks坐标轴刻度线 axis.ticks.xaxis.ticks.y
在设置上述属性时,需要使用element_line()函数,element_line()的定义为:
element_line(
colour = NULL,
size = NULL,
linetype = NULL,
lineend = NULL,
color = NULL,
arrow = NULL,
inherit.blank = FALSE
)
其中,
-
colour/color表示线条的颜色 -
size线条的粗细 -
linetypex线型 -
lineend线条结束位置的形状(是圆的还是方的) -
arrow箭头,参考上篇文章的内容 inherit.blank
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
p + theme(
panel.border = element_blank(),
axis.line = element_line(color="black"),
axis.ticks = element_line(color="red", size=2),
panel.grid.major = element_line(color="blue"),
panel.grid.minor = element_line(color="green")
)

线条元素的主题设置示例
3 矩形元素的外观
常见的矩形元素包括:
-
rect所有的矩形元素 -
lengend.background图例的背景 -
panel.background绘图区域的背景 -
panel.border绘图区域的边框 -
plot.background整个图形的背景 -
strip.background分面标签的背景
在设置上述属性时,需要使用element_rect()函数,其定义为:
element_rect(
fill = NULL,
colour = NULL,
size = NULL,
linetype = NULL,
color = NULL
)
该函数比较简单,所有的参数均在前面有所介绍,在此不再赘述了。下面来看几个例子就好:
p +
theme(
panel.background=element_rect(
fill="pink",
color="black",
size=2
)
)

矩形元素的主题设置
4 主题的设置与自定义
ggplot2中已经包含了许多预定的主题,系统默认的主题为theme_gray(),系统中自带的主题包括:
theme_bw()theme_minimal()theme_classic()theme_void()
如果想设置某个主题,除了常规的用加号来实现主题的加载外,还可以使用theme_set()来设置主题,例如:
theme_set(theme_classic())
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
p
theme_set(theme_gray())

主题设置
mytheme <- theme_bw() + theme(
text = element_text(color="red"),
axis.title = element_text(size=rel(1.25))
)
p + mytheme

自定义主题