# 准备数据

``````# Convert dose column dose from a numeric to a factor variable
ToothGrowth\$dose <- as.factor(ToothGrowth\$dose)
##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5
``````

# 示例图

``````library(ggplot2)
# Box plot
bp <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
bp
# scatter plot
sp<-ggplot(cars, aes(x = speed, y = dist)) + geom_point()
sp
``````

img
img

# 改变x和y轴刻度

• `xlim()``ylim()`
• `expand_limits()`
• `scale_x_continuous()``scale_y_continuous()`

## 使用xlim()和ylim()函数

``````# x axis limits
sp + xlim(min, max)
# y axis limits
sp + ylim(min, max)
``````

min和max是每个轴的最小值和最大值。

``````# Box plot : change y axis range
bp + ylim(0,50)
# scatter plots : change x and y limits
sp + xlim(5, 40)+ylim(0, 150)
``````

img
img

## 使用expand_limts()函数

• 快速设置在x和y轴在 (0,0) 处的截距项
• 改变x和y轴范围
``````# set the intercept of x and y axis at (0,0)
sp + expand_limits(x=0, y=0)
# change the axis limits
sp + expand_limits(x=c(0,30), y=c(0, 150))
``````

img
img

## 使用scale_xx()函数

``````scale_x_continuous(name, breaks, labels, limits, trans)
scale_y_continuous(name, breaks, labels, limits, trans)
``````
• name：x或y轴标签
• breaks：控制引导元素的刻度（轴刻度，网格线等），可以使用
• NULL : 隐藏所有刻度
• waiver() : 默认刻度
• 一个字符串或数值向量指定显示的刻度
• 标签：刻度值标签，可以使用下面的值：
• NULL 没标签
• waiver() 默认标签
• character vector 指定标签
• limits：指定刻度范围
• trans：轴转换，可以使用 “log2”, “log10”, …

``````# Change x and y axis labels, and limits
sp + scale_x_continuous(name="Speed of cars", limits=c(0, 30)) +
scale_y_continuous(name="Stopping distance", limits=c(0, 150))
``````

img

# 轴转换

## 对数化和开方转换

• scale_x_log10(), scale_y_log10() : for log10 transformation
• scale_x_sqrt(), scale_y_sqrt() : for sqrt transformation
• scale_x_reverse(), scale_y_reverse() : to reverse coordinates
• coord_trans(x =“log10”, y=“log10”) : possible values for x and y are “log2”, “log10”, “sqrt”, …
• scale_x_continuous(trans=‘log2’), scale_y_continuous(trans=‘log2’) : another allowed value for the argument trans is ‘log10’

``````# Default scatter plot
sp <- ggplot(cars, aes(x = speed, y = dist)) + geom_point()
sp
# Log transformation using scale_xx()
# possible values for trans : 'log2', 'log10','sqrt'
sp + scale_x_continuous(trans='log2') +
scale_y_continuous(trans='log2')
# Sqrt transformation
sp + scale_y_sqrt()
# Reverse coordinates
sp + scale_y_reverse()
``````

img
img
img
img

``````# Possible values for x and y : "log2", "log10", "sqrt", ...
sp + coord_trans(x="log2", y="log2")
``````

img

## 格式化轴刻度标签

``````# Log2 scaling of the y axis (with visually-equal spacing)
library(scales)
sp + scale_y_continuous(trans = log2_trans())
# show exponents
sp + scale_y_continuous(trans = log2_trans(),
breaks = trans_breaks("log2", function(x) 2^x),
labels = trans_format("log2", math_format(2^.x)))
``````

img
img

Note that many transformation functions are available using the scales package : log10_trans(), sqrt_trans(), etc. Use help(trans_new) for a full list.

``````library(scales)
# Percent
sp + scale_y_continuous(labels = percent)
# dollar
sp + scale_y_continuous(labels = dollar)
# scientific
sp + scale_y_continuous(labels = scientific)
``````

img
img
img

## 显示对数化刻度标记

Note that, these tick marks make sense only for base 10

``````library(MASS)
##                     body brain
## Mountain beaver     1.35   8.1
## Cow               465.00 423.0
## Grey wolf          36.33 119.5
## Goat               27.66 115.0
## Guinea pig          1.04   5.5
## Dipliodocus     11700.00  50.0
``````

``````library(MASS) # to access Animals data sets
library(scales) # to access break formatting functions
# x and y axis are transformed and formatted
p2 <- ggplot(Animals, aes(x = body, y = brain)) + geom_point() +
scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
labels = trans_format("log10", math_format(10^.x))) +
scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
labels = trans_format("log10", math_format(10^.x))) +
theme_bw()
# log-log plot without log tick marks
p2
# Show log tick marks
p2 + annotation_logticks()
``````

img
img

Note that, default log ticks are on bottom and left.

``````# Log ticks on left and right
p2 + annotation_logticks(sides="lr")
# All sides
p2+annotation_logticks(sides="trbl")
``````

• t : for top
• r : for right
• b : for bottom
• l : for left
• the combination of t, r, b and l

# 格式化日期轴

## 创建时间序列数据

``````df <- data.frame(
date = seq(Sys.Date(), len=100, by="1 day")[sample(100, 50)],
price = runif(50)
)
df <- df[order(df\$date), ]
##          date      price
## 33 2016-09-21 0.07245190
## 3  2016-09-23 0.51772443
## 23 2016-09-25 0.05758921
## 43 2016-09-26 0.99389551
## 45 2016-09-27 0.94858770
## 29 2016-09-28 0.82420890
``````

## 绘制日期

``````# Plot with date
dp <- ggplot(data=df, aes(x=date, y=price)) + geom_line()
dp
``````

img

## 格式化日期标记

``````library(scales)
# Format : month/day
dp + scale_x_date(labels = date_format("%m/%d")) +
theme(axis.text.x = element_text(angle=45))
# Format : Week
dp + scale_x_date(labels = date_format("%W"))
# Months only
dp + scale_x_date(breaks = date_breaks("months"),
labels = date_format("%b"))
``````

img
img
img

Note that, since ggplot2 v2.0.0, date and datetime scales now have date_breaks, date_minor_breaks and date_labels arguments so that you never need to use the long scales::date_breaks() or scales::date_format().

## 日期轴范围

``````head(economics)
##         date   pce    pop psavert uempmed unemploy
## 1 1967-07-01 507.4 198712    12.5     4.5     2944
## 2 1967-08-01 510.5 198911    12.5     4.7     2945
## 3 1967-09-01 516.3 199113    11.7     4.6     2958
## 4 1967-10-01 512.9 199311    12.5     4.9     3143
## 5 1967-11-01 518.1 199498    12.5     4.7     3066
## 6 1967-12-01 525.8 199657    12.1     4.8     3018
``````

Create the plot of psavert by date :

• date : Month of data collection
• psavert : personal savings rate
``````# Plot with dates
dp <- ggplot(data=economics, aes(x=date, y=psavert)) + geom_line()
dp
# Axis limits c(min, max)
min <- as.Date("2002-1-1")
max <- max(economics\$date)
dp+ scale_x_date(limits = c(min, max))
``````

img
img

# 进一步

原文作者：王诗翔
原文地址: https://www.jianshu.com/p/03255dd4324d
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。