作者:Li_Yuhui
四川大学研究生在读
本文是ggplot2_可视化_速成的第3节
第2节:coor_xxx()
坐标系变换
第4节:facet_xxx()
分面系统
第5节:Guides图例与增加坐标轴
第6节:themes主题系统
scale_xxx()
标度调整
标度用于控制变量映射到视觉对象的具体细节,如坐标轴标签和图例
视觉对象分为:
坐标轴,alpha透明度,color/fill颜色,date/time时间轴, hue色相, grey灰度,
shape点形, size尺寸, linetype线型, radius半径, area面积
它们都有相应的标度函数
分为简单函数和复合函数,复合函数内包含简单函数,简单函数如下:
函数名称 | 描述 |
---|---|
xlab() | 指定x轴的名称 |
ylab() | 指定y轴的名称 |
ggtitle() | 指定标题和副标题的内容 |
labs() | 指定坐标轴的名称,和其它映射参数在图例中的名称,还包括标题title、副标题subtitle和底部注释caption的内容 |
xlim() | 指定x轴的显示范围,反区间表示坐标轴顺序翻转,如xlim(20, 15) 表示x轴范围从20(左边)显示到15(右边) |
ylim() | 指定y轴的显示范围,同样支持反区间操作,使坐标轴顺序翻转 |
lims() | 指定其它映射参数在在图中的显示范围,不在范围的也不会显示在图例中 |
expand_limits() | 扩展映射参数的显示范围,不能缩小,只能扩展 |
复合标度函数:
除去默认的8个系统默认的标度scale_xxx_identity()
,软件默认的一般用不上,用得上就不需要改了,
这8个分别是:
scale_color_identity()
, scale_fill_identity()
, scale_shape_identity()
, scale_linetype_identity()
,
scale_alpha_identity()
, scale_size_identity()
, scale_discrete_identity()
, scale_continuous_identity()
还有一个手动处理任意离散变量的标度函数scale_discrete_manual(),其增加了1个映射参数,如aesthetics = c("color", "fill")
现在还剩下11组标度函数,分类如下:
视觉对象 | 变量类型 | 标度函数 | 描述及关键参数 |
---|---|---|---|
轴 | 连续变量 | scale_x_continuous() | name,breaks,labels,limits,expand, trans,postion |
scale_y_continuous() | 还有:minor_breaks, sec.axis 更多trans及自定义 | ||
scale_x_log10()/sqrt() | 只有trans参数不一样,相当于trans=“log10”/“sqrt” | ||
scale_x_log10()/sqrt() | |||
scale_x_reverse() | 翻转x轴,相当于trans=“reverse”,其它参数相同 | ||
scale_y_reverse() | |||
离散变量 | scale_x_discrete() | name,breaks,labels,limits,expand,na.value, position | |
scale_y_discrete() | 与上面相同 | ||
颜色 | 连续变量 | scale_colour_continuous() | type=“gradient”, type=“viridis”(色盲渐变) |
scale_fill_continuous() | |||
连续色板 | scale_colour_distiller() | 将离散色板连续化,来自RColorBrewer色板,type,palette, direction | |
scale_fill_distiller() | |||
连续渐变 | scale_colour_gradient() | 单极渐变, low,high | |
scale_colour_gradient2() | 两极渐变, low,mid,hight | ||
scale_colour_gradientn() | 多色渐变,colors,如colours = terrain.colors(10) | ||
scale_fill_gradient() | |||
scale_fill_gradient2() | |||
scale_fill_gradientn() | |||
离散色板 | scale_colour_brewer() | type, palette,direction指定标度顺序(1/-1) | |
scale_fill_brewer() | |||
自定义 | scale_colour_manual() | values,默认名称属性匹配,否则字母顺序匹配, 因子水平匹配最好 | |
scale_fill_manual() | |||
透明度 | 连续变量 | scale_alpha() | range,limits, breaks, labels |
scale_alpha_continuous() | range,limits, breaks, labels | ||
离散变量 | scale_alpha_discrete() | range,limits, breaks, lables | |
scale_alpha_ordinal() | range,limits, breaks, labels | ||
自定义 | scale_alpha_manual() | values | |
色相 | 离散变量 | scale_colour_hue() | h, c, l, h.start, direction |
scale_fill_hue() | h, c, l, h.start, direction | ||
灰度 | 连续渐变 | scale_colour_grey() | start, end |
scale_fill_grey() | start, end | ||
shape | 离散变量 | scale_shape() | name, limits, breaks, labels |
自定义 | scale_shape_manual() | values | |
线型 | 连续变量 | scale_linetype_continuous() | name, limits, breaks, labels,不常用连续变量 |
离散变量 | scale_linetype() | name, limits, breaks, labels | |
scale_linetype_discrete() | name, limits, breaks, labels | ||
自定义 | scale_linetype() | values | |
尺寸 | 数值 | scale_radius() | 圆半径,name,limits, breaks, labels, range |
数值 | scale_size() | size面积/线宽,参数与radius相同。不建议size映射离散变量 | |
数值 | scale_size_area() | area面积,0映射到零面积,参数与上面相同 | |
自定义 | scale_size_manual() | values | |
时间 | 时间序列 | scale_x_date() | 用于时间轴的标度设置,参数包括:name, breaks,labels |
scale_y_date() | 和:date_breaks(时间跨度), date_labels,limits, expand,position 等 | ||
scale_x_time() | 参数与_date()相同,增加obb参数(out of bounds)处理limits外的数据 | ||
scale_y_time() | |||
scale_x_datetime() | 参数比xxx_date()增加了:timezone | ||
scale_y_datetime() | |||
色盲 | 离散变量 | scale_colour_viridis_d() | 色盲友好颜色,使用viridis colormap色板,参数与下面相同 |
scale_fill_viridis_d() | alpha, begin, end, direction,option,option指定具体的色条 | ||
连续渐变 | scale_colour_viridis_c() | 参数与上面相同,option: “A”=“magma”, “B”=“inferno” | |
scale_fill_viridis_c() | option: “C”=“plasma”, “D”=“viridis”(默认), “E”=“cividis” |
坐标轴标度与scales包
视觉对象 | 变量类型 | 标度函数 | 描述及关键参数 |
---|---|---|---|
轴 | 连续变量 | scale_x_continuous() | name,breaks,labels,limits,expand, trans,postion |
scale_y_continuous() | 还有:minor_breaks, sec.axis | ||
scale_x_log10()/sqrt() | 只有trans参数不一样,相当于trans=“log10”/“sqrt” | ||
scale_x_log10()/sqrt() | |||
scale_x_reverse() | 翻转x轴,相当于trans="reverse"和limits反区间,其它参数相同 | ||
scale_y_reverse() | |||
离散变量 | scale_x_discrete() | name,breaks,labels,limits,expand,na.value, position | |
scale_y_discrete() | 与上面相同 |
参数解释:
- name 表示指定坐标轴名称,也将作为对应的图例名称
- breaks 表示指定坐标轴刻度位置,即粗网格线位置
- labels 表示指定坐标轴刻度标签内容
- limits 表示指定坐标轴显示范围,支持反区间
- expand 表示扩展坐标轴显示范围,不能缩小
- trans 表示指定坐标轴变换函数,自带有"asn",“atanh”,“boxcox”,“exp”,“identity”,“log”,“log10”,“log1p”,“log2”,“logit”,“probability”,
“probit”,“reciprocal”。还支持scales包内的其它变换函数,如scales::percent()
百分比刻度,自定义scales::trans_new()
- position 表示指定坐标轴显示位置,x轴为"left"和"right", y轴为"top"和"bottom"
- minor_breaks 表示指定细网格线对应位置,细网线没有标签对应,没有labels参数
- sec.axis 表示是否开启次坐标轴
例:
library(ggplot2)
p1 <- ggplot(mpg, aes(displ, hwy)) +
geom_point()
p1
p1 +
scale_x_continuous(name = "发动机排量/L", limits = c(2,6), breaks = c(2, 4, 6), labels = c("two", "four", "six"),
minor_breaks = c(3, 5)) + # 重新指定坐标轴名称, 只显示区间(2, 6)范围的元素, 更改坐标轴刻度和标签
scale_y_continuous(name = "高速公路油耗" ) # 重新指定坐标轴名称
set.seed(14)
df <- data.frame(
x = rnorm(10) * 100000,
y = seq(0, 1, length.out = 10)
)
p2 <- ggplot(df, aes(x, y)) + geom_point(shape=21, color = "purple", fill = "cyan", size = 5)
p2 + scale_y_continuous(labels = scales::percent) # y轴百分号显示
p2 + scale_x_continuous(labels = scales::comma) + # 数字逗号分割,每3位数增加1个逗号
scale_y_continuous(labels = scales::dollar) # y轴美元单位显示
颜色fill/color,灰度grey,色相hue, 色盲颜色
视觉对象 | 变量类型 | 标度函数 | 描述及关键参数 |
---|---|---|---|
颜色 | 连续变量 | scale_colour_continuous() | type=“gradient”, type=“viridis”(色盲渐变) |
scale_fill_continuous() | |||
连续色板 | scale_colour_distiller() | 将离散色板连续化,来自RColorBrewer色板,type,palette, direction | |
scale_fill_distiller() | |||
连续渐变 | scale_colour_gradient() | 单极渐变, low,high | |
scale_colour_gradient2() | 两极渐变, low,mid,hight | ||
scale_colour_gradientn() | 多色渐变,colors,如colours = terrain.colors(10) | ||
scale_fill_gradient() | |||
scale_fill_gradient2() | |||
scale_fill_gradientn() | |||
离散色板 | scale_colour_brewer() | type, palette,direction指定标度顺序(1/-1) | |
scale_fill_brewer() | |||
自定义 | scale_colour_manual() | values,默认名称属性匹配,否则字母顺序匹配, 因子水平匹配最好 | |
scale_fill_manual() | |||
透明度 | 连续变量 | scale_alpha() | range,limits, breaks, labels |
scale_alpha_continuous() | range,limits, breaks, labels | ||
离散变量 | scale_alpha_discrete() | range,limits, breaks, lables | |
scale_alpha_ordinal() | range,limits, breaks, labels | ||
自定义 | scale_alpha_manual() | values | |
色相 | 离散变量 | scale_colour_hue() | h, c, l, h.start, direction |
scale_fill_hue() | h, c, l, h.start, direction | ||
灰度 | 连续渐变 | scale_colour_grey() | start, end |
scale_fill_grey() | start, end | ||
色盲 | 离散变量 | scale_colour_viridis_d() | 色盲友好颜色,使用viridis colormap色板,参数与下面相同 |
scale_fill_viridis_d() | alpha, begin, end, direction,option,option指定具体的色条 | ||
连续渐变 | scale_colour_viridis_c() | 参数与上面相同,option: “A”=“magma”, “B”=“inferno” | |
scale_fill_viridis_c() | option: “C”=“plasma”, “D”=“viridis”(默认), “E”=“cividis” |
参数解释:
- type 在
scale_color_continuous
中表示指定变化类型,是普通渐变"gradient"还是色盲渐变"viridis"
在scale_xxx_distiller()
中表示指定色板类型,是"seq"渐变,"qual"离散对比,还是"div"两极色板 - palette 表示指定色条类型,当type色板类型已经指定的情况下,可以用序号指定,若type未指定,则必须用色条名称指定
- direction 表示指定标度与变量的匹配方向,direction=-1表示方向翻转
在scale_xxx_hue()
中,direction=1表示色轮的顺时针方向,direction=-1表示逆时针方向 - low, high表示渐变的颜色两极颜色名称或HEX色值,如果用颜色名称指定,则可用
muted("color")
指定某个暗色 - mid 表示指定渐变的中点颜色
- midpoint 表示指定渐变的中点对应的变量值
- colors/colours 多色渐变中,指定颜色向量, 如
colour = terrain.colors(10)
取10个地形图颜色作为渐变的基础色 - values 表示指定自定义颜色向量,如果变量为数字类型,则默认按数字大小顺序与values匹配,
如果变量为字符类型,则默认按变量字母顺序与values匹配,
为了按照想要的顺序匹配,可以给变量增加一个因子水平,然后自动按照因子水平与values匹配(自上而下,由低到高)
也可给values向量设置名称属性,名称与要映射的变量值一样,然后按照名称属性匹配 - range 表示指定指定显示的透明度范围,在[0, 1]区间内,0表示不透明,1表示不透明
- limits 表示设定显示范围
- breaks 表示设定图例刻度位置
- labels 表示指定图例刻度处显示标签
- h 表示指定色相范围,在区间[0, 360]内
- c 表示指定chroma(色度,鲜艳或是暗淡)值,最大值取决于hue和luminance
- l 表示指定luminance(亮度),在区间[0, 100]内
- start 表示指定灰度起点,从0到1,0表示白色,1表示黑色
- end 表示灰度结束点,通常end,默认end更黑,若设定start>end,则翻转标度
- end 表示灰度结束点,通常end,默认end更黑
- 其它公共参数:name图例名称,palette, breaks, labels, limits, expand, position(标签在图例的上\下\左\右)
- 只有连续的标度函数,如
scale_xxx_gradient^()
才支持trans内置参数
色轮图:
以红色和橙色的界限作为0刻度,开始旋转
color/fill
library(ggplot2)
# scale_fill_continuous
v <- ggplot(faithfuld, aes(waiting, eruptions, fill = density)) +
geom_tile()
v
v + scale_fill_continuous(type = "gradient", name = "密度", breaks = c(0, 0.05, 0.01, 0.02, 0.03, 0.04),labels = c(0, 0.05, 0.01, 0.02, 0.03, 0.04), position = "left")# 更改图例名称,不支持刻度点,图例标签位置,匹配方向等参数
v + scale_fill_continuous(type = "viridis" ) # 结果与scale_fill_viridis_c()一样
# scale_color_distiller
set.seed(19)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
(d <- ggplot(dsamp, aes(carat, price)) +
geom_point(aes(colour = clarity)))
v <- ggplot(faithfuld) +
geom_tile(aes(waiting, eruptions, fill = density))
v
v + scale_fill_distiller(palette = "Spectral", breaks = c(0, 0.05, 0.01, 0.02, 0.03, 0.04), labels = c(0, 0.05, 0.01, 0.02, 0.03, 0.04)) # 更改图例刻度及标签失败
# scale_xxx_gradient^()
set.seed(18)
df <- data.frame(
x = runif(100),
y = runif(100),
z1 = rnorm(100),
z2 = abs(rnorm(100))
)
ggplot(df, aes(x, y)) +
geom_point(aes(colour = z2)) # 默认从light blue到dark blue
ggplot(df, aes(x, y)) +
geom_point(aes(colour = z2)) +
scale_colour_gradient(low = "white", high = "black", name = "这是图例名称", breaks = c(0, 0.5, 1, 2, 3, 4),labels = c(0, 0.5, 1, 2, 3, 4)) # 灰度渐变,修改图例名称,图例刻度及刻度标签
ggplot(df, aes(x, y)) +
geom_point(aes(colour = z1), size = 2) +
scale_colour_gradient2() # 两极渐变,
ggplot(df, aes(x, y)) +
geom_point(aes(fill = z2), shape = 21, size = 3) +
scale_fill_gradient2(low = "blue", mid = "red", midpoint = 2, high = "cyan", name = "这是图例名称") # 修改基础颜色,
ggplot(df, aes(x, y)) +
geom_point(aes(colour = z1)) +
scale_colour_gradientn(colours = terrain.colors(10), name = "这是图例名称") # 应用terrain.colors内置色板,更改标度方向失败
library(ggplot2)
# scale_color_brewer
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
(d <- ggplot(dsamp, aes(carat, price)) +
geom_point(aes(colour = clarity)))
d + scale_colour_brewer(name = "钻石透明度", palette= "Greens", direction = -1, position = "left") # 更改图例名称,色板,标度方向,更改位置失败
d + scale_colour_brewer(palette = "Set1", name = "钻石透明度") # 多种颜色也可以渐变,非常方便
# scale_color_manual
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_point(aes(colour = factor(cyl)))
p + scale_colour_manual(values = c("red", "blue", "green"))
# 按名称属性匹配
cols <- c("8" = "red", "4" = "blue", "6" = "darkgreen", "10" = "orange") # 设定名称属性
p + scale_colour_manual(values = cols) # 名称属性匹配
p + scale_colour_manual(
name = "这是图例名字",
values = cols,
breaks = c("4", "6", "8"),
labels = c("four", "six", "eight"),
limits = c("4", "6", "8", "10")
)
透明度、色相、灰度
library(ggplot2)
p <- ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(alpha = year))
p
p + scale_alpha(range = c(0.4, 0.8), name = "这是图例名称") # 设定透明度范围为0.4到0.8
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
d <- ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity))
d + scale_colour_hue(name = "这是图例名称") # 默认全色轮
d + scale_colour_hue(l = 70, c = 150, name = "这是图例名称")# 调整色度和亮度
d + scale_colour_hue(h = c(0, 90), "这是图例名称") # 设定色相范围,0代表红色与橙色的分界
d + scale_colour_hue(h = c(90, 180), "这是图例名称")
d + scale_colour_hue(h = c(270, 360), "这是图例名称")
# 灰度
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl)))
p + scale_colour_grey()
p + scale_colour_grey(start = 0.8, end = 0.2, name = "这是图例名称") # 修改灰度范围
# 灰度增加缺失值映射
miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE))
ggplot(mtcars, aes(mpg, wt)) +
geom_point(aes(colour = miss)) + # 若缺失向量是data数据的子集,则可以映射
scale_colour_grey(na.value = "green", name = "这是图例名称") # 增加缺失值为绿色
色盲友好色
library(ggplot2)
# 离散变量
txsamp <- subset(txhousing, city %in%
c("Houston", "Fort Worth", "San Antonio", "Dallas", "Austin"))
d <- ggplot(data = txsamp, aes(x = sales, y = median)) +
geom_point(aes(colour = city))
d
d + scale_colour_viridis_d() # 默认viridis色板
d + scale_colour_viridis_d(option = "plasma", name = "这是图例名称") # 更改色板为plasma
d + scale_colour_viridis_d(option = "B", name = "这是图例名称") # 更改色板为inferno
d + scale_colour_viridis_d(option = "magma", name = "这是图例名称")
d + scale_colour_viridis_d(option = "cividis", name = "这是图例名称")
# 连续变量
v <- ggplot(faithfuld) +
geom_tile(aes(waiting, eruptions, fill = density))
v + scale_fill_viridis_c()
v + scale_fill_viridis_c(option = "plasma", name = "这是图例名称")
shape点型,linetype线型
视觉对象 | 变量类型 | 标度函数 | 描述及关键参数 |
---|---|---|---|
shape | 离散变量 | scale_shape() | name, limits, breaks, labels |
自定义 | scale_shape_manual() | values | |
线型 | 连续变量 | scale_linetype_continuous() | name, limits, breaks, labels,不常用连续变量 |
离散变量 | scale_linetype() | name, limits, breaks, labels | |
scale_linetype_discrete() | name, limits, breaks, labels |
参数解释:
- name 表示指定图例的名称
- breaks 表示指定图例的刻度位置
- labels 表示指定图例刻度的显示标签
- limits 表示指定该标度显示范围
- values 为向量,表示手动指定shape,通过给变量增加一个因子水平,然后就按因子水平与values对应顺序匹配
- direction 表示指定标度匹配顺序
set.seed(15)
dsmall <- diamonds[sample(nrow(diamonds), 100), ]
d <- ggplot(dsmall, aes(carat, price)) + geom_point(aes(shape = cut),color = "blue", position = position_jitter(width = 0.1, height = 0.3))
d
d + scale_shape(name = "钻石切割水平", breaks = c("Fair", "Good", "Very Good", "Premium", "Ideal"), labels = c("一般", "还行", "很好", "上好", "顶级")) # 设置图例的名称和刻度标签
oneshape <- c(25:21)
levels(dsmall$cut) <- c("Fair", "Good", "Very Good", "Premium", "Ideal") # 给要映射的变量增加因子水平,然后通过因子水平匹配
dsmall <- diamonds[sample(nrow(diamonds), 100), ]
d <- ggplot(dsmall, aes(carat, price)) + geom_point(aes(shape = cut),color = "blue", position = position_jitter(width = 0.1, height = 0.3)) #
d + scale_shape_manual(values = oneshape, name = "切割工艺") # values的顺序与变量的因子水平一致
尺寸(size/area/radius)
视觉对象 | 变量类型 | 标度函数 | 描述及关键参数 |
---|---|---|---|
尺寸 | 数值 | scale_radius() | 圆半径,name,limits, breaks, labels, range, trans |
数值 | scale_size() | size面积/线宽,参数与radius相同。不建议size映射离散变量 | |
数值 | scale_size_area() | area面积,0映射到零面积,没有trans和range参数, 新增max_size参数 | |
自定义 | scale_size_manual() | values |
参数解释:
- name 表示指定在所对应图例的标题内容
- limits 表示设置显示范围,其变量的范围,不是尺寸的范围
- breaks 表示指定图例刻度位置
- labels 表示指定图例刻度显示标签
- range 表示指定trans转化后半径/线宽后的尺寸显示范围,与limits参数不同
- trans 表示指定尺寸转化公式,指定后尺寸与变量不是线性关系
例:
p <- ggplot(mpg, aes(displ, hwy, size = hwy)) +
geom_point(position = position_jitter(width = 0.1, height = 0.2), shape = 21, fill = "green")
p
p + scale_radius(name = "高速公路油耗", range = c(2, 10), limits = c(0, 30))# 指定半径从2变化到10,即最小半径为2,最大半径为10,只显示值小于30的数据点
p + scale_size(name = "高速公路油耗", range = c(2, 10), limits = c(0, 30),
breaks = c(2, 12, 25, 30), labels = c("2L", "12L", "25L", "30L")) # 设置图例刻度及标签
p + scale_size_area(name = "高速公路油耗", max_size = 8,
breaks = c(2, 12, 25, 30), labels = c("2L", "12L", "25L", "30L")) # 指定最大面积为8,最小面积从0开始
时间轴
视觉对象 | 变量类型 | 标度函数 | 描述及关键参数 |
---|---|---|---|
时间 | 时间序列 | scale_x_date() | 用于时间轴的标度设置,参数包括:name, breaks,labels |
scale_y_date() | 和:date_breaks(时间跨度), date_labels,limits, expand,position 等 | ||
scale_x_time() | 参数与_date()相同,增加obb参数(out of bounds)处理limits外的数据 | ||
scale_y_time() | |||
scale_x_datetime() | 参数比xxx_date()增加了:timezone | ||
scale_y_datetime() |
所谓时间轴,就是当横轴或纵轴是由时间、日期序列映射产生的。
scale_xxx_date()
要求变量是Date格式scale_xxx_datetime()
要求变量是POSIXct格式scale_xxx_time()
要求变量是hms格式
参数解释:- name 表示指定坐标轴名称
- breaks 表示指定坐标轴刻度位置,即粗网格线位置, Date/POSIXct向量格式
- labels 表示指定坐标轴刻度显示标签,即breaks点显示文字内容
- date_breaks 表示指定时间跨度(如"2 weeks", “10 years”),当与breaks同时指定时,优先级高于breaks
- date_labels 刻度显示标签,
strftime()
格式, 如果与labels同时指定,优先级高于labels - minor_breaks 表示细网格刻度位置,与breaks类型相同
- date_minor_breaks 与date_breaks类型相同,表示细网格跨度
- limits 表示指定显示范围
- expand 表示扩展显示范围
- position 表示时间轴位置,x为"top"或"bottom", y为"left"和"right"
- timezone 表示切换时区,默认为原时间时区
- obb 表示指定处理在limits之外是时间函数, 默认为NA
例:
library(ggplot2)
last_month <- Sys.Date() - 0:29
set.seed(16)
df <- data.frame(
date = last_month,
price = runif(30)
)
base <- ggplot(df, aes(date, price)) + geom_line()
base + scale_x_date(name = "日期", date_labels = "%b %d") # 格式化参数,%b表示月份英文缩小,%d表示月份中第几天
base + scale_x_date(name = "日期", date_breaks = "1 week", date_labels = "第%W周",date_minor_breaks = "1 day", limits = c(Sys.Date() - 7, NA)) # 时间跨度为1周,%W表示年内的星期数,第几周, 设定细网格时间跨度为1天, 设定显示范围为7天前至今