# 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))
轴转换
对数化和开方转换
内置转换函数:
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()
# 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()
函数**coord_trans()**也可以用于轴坐标转换
# Possible values for x and y : "log2", "log10", "sqrt", ...
sp + coord_trans(x="log2", y="log2")
格式化轴刻度标签
这需要加载
scales
包:
# 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)))
“Note that many transformation functions are available using the
scales
package : log10_trans(), sqrt_trans(), etc. Use help(trans_new) for a full list.
“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().