Axes
本文档介绍ggplot绘图中对axes的修改。在文档开始之前,先看看ggplot2默认的图例:
library(ggplot2)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
bp
1
2
3
2
3
# 1. 交换X和Y轴
bp + coord_flip()
1
# 2. 离散型坐标轴
# 2.1. 改变离散型刻度顺序
# Manually set the order of a discrete-valued axis
bp + scale_x_discrete(limits=c("trt1","trt2","ctrl"))
1
2
2
只改变坐标轴,不会改变legend
# 2.2. 设置刻度线标签
bp + scale_x_discrete(breaks=c("ctrl", "trt1", "trt2"),
labels=c("Control", "Treat 1", "Treat 2"))
# Hide x tick marks, labels, and grid lines
bp + scale_x_discrete(breaks=NULL)
# Hide all tick marks and labels (on X axis), but keep the gridlines
bp + theme(axis.ticks = element_blank(), axis.text.x = element_blank())
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3. 连续型坐标轴
# 3.1. 设置坐标轴范围
如果只是简单的想要坐标轴包含范围内的特定值,可以使用 expand_limits()
。这只能扩大一个轴的范围;它不能缩小范围。
# Make sure to include 0 in the y axis
bp + expand_limits(y=0)
# Make sure to include 0 and 8 in the y axis
bp + expand_limits(y=c(0,8))
1
2
3
4
5
6
2
3
4
5
6
在这个例子中,
bp + expand_limits(y=c(0,5))
与bp + expand_limits(y=0)
将得到相同的图,因为原图坐标轴已经包含了5
此外,可以明确的设置坐标轴的上下限,使用ylim
或者 scale_y_continuous
,需要注意的是,只要使用了scale_y_continuous
,ylim
将失效
# Set the range of a continuous-valued axis
# These are equivalent
bp + ylim(0, 8)
# bp + scale_y_continuous(limits=c(0, 8))
bp + ylim(4, 6)
# 如果ylim 不包含全部数据范围,会提示warning信息
# Warning message:
# Removed 6 rows containing non-finite values (stat_boxplot).
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 3.2. 反转坐标轴方向
# Reverse order of a continuous-valued axis
bp + scale_y_reverse()
1
2
2
# 3.3. 设置和隐藏刻度
# Setting the tick marks on an axis
# This will show tick marks on every 0.25 from 1 to 10
# 绘制刻度在(3.50-6.25)之间的数据
bp + scale_y_continuous(breaks=seq(1,10,1/4))
# 刻度可以是不均匀的
bp + scale_y_continuous(breaks=c(4, 4.25, 4.5, 5, 6,8))
# 隐藏刻度、和网格线
bp + scale_y_continuous(breaks=NULL)
# 隐藏刻度ticks、刻度标签,但保留网格线
bp + theme(axis.ticks = element_blank(), axis.text.y = element_blank())
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 3.4. 坐标轴转换(log、sqrt)
坐标轴默认是线性的,也可以对其进行转换(log, power, roots等)
有两种变换轴的方法。一种是使用尺度变换(scale),另一种是使用坐标变换(coordinate)。
- 尺度变换,数据变换发生刻度(ticks)、轴范围(range)等属性确定之前;
- 坐标变换,变换发生刻度(ticks)、轴范围(range)等属性确定之后。
这会导致不同的外观,如下所示。
# Create some noisy exponentially-distributed data
set.seed(201)
n <- 100
dat <- data.frame(
xval = (1:n+rnorm(n,sd=5))/20,
yval = 2*2^((1:n+rnorm(n,sd=5))/20)
)
# A scatterplot with regular (linear) axis scaling
sp <- ggplot(dat, aes(xval, yval)) + geom_point()
sp
# log2 scaling of the y axis (with visually-equal spacing)
library(scales) # Need the scales package
sp + scale_y_continuous(trans=log2_trans())
# log2 coordinate transformation (with visually-diminishing spacing)
sp + coord_trans(y="log2")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
通过比例变换,可以顺便设置坐标轴刻度线和label。
sp + scale_y_continuous(trans = log2_trans(),
breaks = trans_breaks("log2", function(x) 2^x),
labels = trans_format("log2", math_format(2^.x)))
1
2
3
2
3
# 3.5. 固定x轴和y轴比率
# Data where x ranges from 0-10, y ranges from 0-30
set.seed(202)
dat <- data.frame(
xval = runif(40,0,10),
yval = runif(40,0,30)
)
sp <- ggplot(dat, aes(xval, yval)) + geom_point()
# Force equal scaling
sp + coord_fixed()
# Equal scaling, with each 1 on the x axis the same length as y on x axis
sp + coord_fixed(ratio=1/3)
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
默认不固定x轴和y轴比率,生成的图可以按照长宽调整形态,而固定之后不管怎么调都不变化。
# 4. 修改坐标轴标签
如果仅改变坐标轴label文本内容,可以通过theme
,xlab|ylab
, scale_x|y_xxxx
, labs
等函数修改。
p1 <- bp + theme(axis.title.x = element_blank()) + # Remove x-axis label
ylab("Weight (Kg)") # Set y-axis label
p2 <- bp + xlab(NULL) + # Remove x-axis label
ylab("Weight (Kg)") # Set y-axis label
# p1 与p2等同
# Also possible to set the axis label with the scale
# x轴label为空字符串,垂直方向label空间保留
p3 <- bp + scale_x_discrete(name="") +
scale_y_continuous(name="Weight (Kg)")
# not show
p4 <- bp + labs(x = NULL, y = "Weight (Kg)")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
使用theme
还可以修改label和刻度的style。
# Change font options:
# X-axis label: bold, red, and 20 points
# X-axis tick marks: rotate 90 degrees CCW, move to the left a bit (using vjust,
# since the labels are rotated), and 16 points
bp + theme(axis.title.x = element_text(face="bold", colour="#990000", size=20),
axis.text.x = element_text(angle=90, vjust=0.5, size=16))
1
2
3
4
5
6
2
3
4
5
6
# 5. 坐标轴刻度格式化输出
格式化坐标轴刻度,e.g. 百分比,科学计数等,可以通过特定的formater
完成
# Label formatters
library(scales) # Need the scales package
bp + scale_y_continuous(labels=percent) +
scale_x_discrete(labels=abbreviate) # In this particular case, it has no effect
# Self-defined formatting function for times.
timeHMS_formatter <- function(x) {
h <- floor(x/60)
m <- floor(x %% 60)
s <- round(60*(x %% 1)) # Round to nearest second
lab <- sprintf('%02d:%02d:%02d', h, m, s) # Format the strings as HH:MM:SS
lab <- gsub('^00:', '', lab) # Remove leading 00: if present
lab <- gsub('^0', '', lab) # Remove leading 0 if present
}
bp + scale_y_continuous(label=timeHMS_formatter)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- 对于连续型变量的,常用的formatters 还包括
comma
,percent
,dollar
, andscientific
. - 对与离散性变量,
abbreviate
将删除元音和空格并缩短为四个字符 - 对于日期,可以用
date_format
# 6. 隐藏网格线
网格线分为major
和 minor
- major: 与刻度对应的网格线
- minor: 刻度以外的辅助线
# 6.1. 隐藏所有垂直和水平网格线
# Hide all the gridlines
bp + theme(panel.grid.minor=element_blank(),
panel.grid.major=element_blank())
# Hide just the minor gridlines
bp + theme(panel.grid.minor=element_blank())
1
2
3
4
5
6
2
3
4
5
6
# 6.2. 隐藏垂直或水平网格线
# Hide all the vertical gridlines
bp + theme(panel.grid.minor.x=element_blank(),
panel.grid.major.x=element_blank())
# Hide all the horizontal gridlines
bp + theme(panel.grid.minor.y=element_blank(),
panel.grid.major.y=element_blank())
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
编辑 (opens new window)
上次更新: 2021/07/08, 21:34:07