基本概念
theme函数是自定义图形的非数据元素外观的一种强大的方法:即标题(title)、标签(label) 、字体(font) 、背景(background) ,网格线(gridlines)和图例(legends) 。
基本用法
theme(主题.部件=element-类型())
主题:
轴线(axis), 图例(legend),面板(panel), 图形(plot), 标签(strip)
部件:
title、text、ticks、line、background、margin、spacing、key、postiton、box、border、switch
类型:
如下表所示👇👇👇
函数 | 内容 | 参数设置 |
---|---|---|
element_blank() | 不绘制任何内容,也不分配任何空间 | |
element_rect() | 边界和背景 | fill、color、linewidth、linetype、size= deprecated()、inherit.blank= FALSE |
element_line() | 线 | color、linewidth、linetype、lineend、arrow、size=deprecated()、inherit.blank=FALSE |
element_text() | 文本 | family、face、color、size、hjust、vjust、angle、lineheight、margin、debug、inherit.blank= FALSE |
PS:
fill——填充颜色
color/colour——线条/边框颜色
linewidth——线条/边框大小(以mm为单位)
linetype——线的类型(blank, solid, dashed, dotted, dotdash, long-dash, twodash)
size——文本大小
lineend——线端样式(round, butt, )
arrow——Arrow规范,由Grid::Arrow()创建
family——字体(例如Times New Roman等)
face——字体类型(“plain”, “italic”, “bold”, “bold.italic”)
hjust——水平对齐,参数范围【0,1】
vjust——垂直对齐,参数范围【0,1】
angle——角度,参数范围【0,360】
lineheight——线的高度
inherit.blank——如果为TRUE,则父元素中存在空白元素将导致该元素也为空白。如果为FALSE,在计算最终元素状态时,任何空白的父元素都将被忽略。
如果对以上基本概念和用法你依旧看不懂: 问题不大,咋er接着聊.........
实战
临渊羡鱼不如退而结网,撸起code加油干。
library(ggplot2)
#创建数据框
p1 <- ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(colour = factor(cyl), shape = factor(vs))) +
labs(title = "Fuel economy declines as weight increases",
x = "Weight (1000 lbs)",
y = "Fuel economy (mpg)",
colour = "black",
shape = "Transmission") +
facet_wrap(~ cyl)
p1
原始图形: (未使用theme函数)
#绘制图形(使用theme函数进行调整)
p1 + theme(#图形调整
plot.title = element_text(size = rel(2)),
plot.background = element_rect(fill = "#E5A0CC"),
#面板元素调整
panel.background = element_rect(fill = "white", colour = "red"),
panel.border = element_rect(linetype = "dotted", fill = NA),
panel.grid.major = element_line(colour = "red"),
#轴线调整
axis.line = element_line(linewidth = 1, colour = "green"),
axis.text = element_text(colour = "black",family = "Times New Roman",size = rel(1),face = "bold"),
axis.ticks.length.y = unit(.25, "cm"),
axis.ticks.length.x = unit(-.25, "cm"),
axis.title = element_text(color = "black",face = "bold"),
axis.text.x = element_text(margin = margin(t = .2, unit = "cm")),
axis.text.y = element_text(margin = margin(r = .2, unit = "cm")),
#图例调整
legend.justification = "top",
legend.box.background = element_rect(),
legend.box.margin = margin(6, 6, 6, 6),
legend.key = element_rect(fill = "white", colour = "white"),
legend.text = element_text(size = 10, colour = "black",face = "bold"),
#图形标签调整
strip.background = element_rect(colour = "#7BAAED", fill = "#7BAAED")
)
哇哇哇哇,这又是什么?
,代码好多看不懂?
不要慌,让一副图片解决所有。请看图:
PS:每一个主题代表不同的颜色;每一个函数具体处理图形的那一部分,我都用箭头给大家在图里面指出来了。如果依旧很懵,大家自行可以在Rstudio里运行一遍。
最后图形配色有点泰裤辣!请大家嘴下留情!!!!