我的数据可视化学习之旅

ggplot2学习(四)

2022-02-21  本文已影响0人  韧心222

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 文本外观

与文本相关的参数主要包括:

在设置上述属性时,需要通过element_text()函数,常用的文本属性包括:

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()函数进行设置,可以使用的参数包括:

在设置上述属性时,需要使用element_line()函数,element_line()的定义为:

element_line(
  colour = NULL,
  size = NULL,
  linetype = NULL,
  lineend = NULL,
  color = NULL,
  arrow = NULL,
  inherit.blank = FALSE
)

其中,

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 矩形元素的外观

常见的矩形元素包括:

在设置上述属性时,需要使用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_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
自定义主题
上一篇 下一篇

猜你喜欢

热点阅读