ggplot2-标度、坐标轴和图例2

1. 中断和标签

当刻度线在坐标轴并且关键字在图例上时,breaks(“中断”)参数控制着哪个值将会出现。每个中断有一个相关的标签,这些标签用labels参数控制。如果设定了labels参数,那么也需要设定breaks参数;否则,数据改变之后中断也不再与标签一致

下面的代码展示了关于坐标轴和图例的一些基本的例子

df <- data.frame(x = c(1, 3, 5) * 1000, y = 1)
axs <- ggplot(df, aes(x, y)) +
	geom_point() +
	labs(x = NULL, y = NULL)

axs
axs + scale_x_continuous(breaks = c(2000, 4000))
axs + scale_x_continuous(breaks = c(2000, 4000), labels = c("2k", "4k"))
leg <- ggplot(df, aes(y, x, fill = x))+
	geom_tile() + labs(x = NULL, y = NULL)

leg
leg + scale_fill_continuous(breaks = c(2000, 40000))
leg + scale_fill_continuous(breaks = c(2000, 4000), labels = c("2k", "4k"))

ggplot2-标度、坐标轴和图例2_第1张图片

ggplot2-标度、坐标轴和图例2_第2张图片

ggplot2-标度、坐标轴和图例2_第3张图片

ggplot2-标度、坐标轴和图例2_第4张图片

ggplot2-标度、坐标轴和图例2_第5张图片

ggplot2-标度、坐标轴和图例2_第6张图片

如果想在分类标度上重新定义中断,可以使用一个命名了的标签向量

df2 <- data.frame(x = 1:3, y = c("a", "b", "c"))
ggplot(df2, aes(x, y)) + geom_point()
ggplot(df2, aes(x, y)) + geom_point() +
	scale_y_discrete(labels = c(a = "apple", b = "banana", c = "carrot"))

ggplot2-标度、坐标轴和图例2_第7张图片

ggplot2-标度、坐标轴和图例2_第8张图片

为了抑制中断(为了坐标轴或网格线)或标签,将它们设为NULL

axs + scale_x_continuous(breaks = NULL)
axs + scale_x_continuous(labels = NULL)

leg + scale_fill_continuous(breaks = NULL)
leg + scale_fill_continuous(labels = NULL)

ggplot2-标度、坐标轴和图例2_第9张图片

ggplot2-标度、坐标轴和图例2_第10张图片

ggplot2-标度、坐标轴和图例2_第11张图片

ggplot2-标度、坐标轴和图例2_第12张图片

此外,可以提供一个函数给breaks或labels
breaks函数应该有一个参数和一个限度(一个长度为2的数值向量),并且应该返回一个数值向量
labels函数应该接受上面的数值向量并返回一个字符串向量(和输入长度相同)
scales包提供了很多有用的标签函数
scales::comma_forma()通过添加逗号来提高比较打的数字的可读性
scales::unit_format(unit, scale)通过添加单位后缀来优化缩放比例
scales::dollar_format(prefix, suffix)展示当前值,四舍五入到两位小数并添加前缀或后缀
scales::wrap_format()将长标签换到多行中

axs + scale_y_continuous(labels = scales::percent_format())
axs + scale_y_continuous(labels = scales::dollar_format("$"))
leg + scale_fill_continuous(labels = scales::unit_format("k", 1e-3))

ggplot2-标度、坐标轴和图例2_第13张图片

可以通过提供位置的数值向量到minor_breaks参数来调整小的断行(在主要的网格线之间的微小的网格线)。这对于对数变换尤其有用

df <- data.frame(x = c(2, 3, 5, 10, 200, 3000), y = 1)
ggplot(df, aes(x, y)) + geom_point() + scale_x_log10()

mb <- as.numeric(1:10 %o% 10 ^ (0:4))
ggplot(df, aes(x, y)) + geom_point() +
	scale_x_log10(minor_breaks = log10(mb))

ggplot2-标度、坐标轴和图例2_第14张图片

ggplot2-标度、坐标轴和图例2_第15张图片

%o%可以快速生成乘法表,并且,在使用转化标度时必须提供小的断行

你可能感兴趣的:(r语言,开发语言)