如何缩放 x 轴并在 R 中添加刻度
How to scale x axis and add ticks in R
我在 R 中使用 geom_histogram 构建了一个直方图,我想将我的 x 轴缩放到 155 insted of 252 显示并查看每个 5 个数字(0、5、10 等) ,我用了scale_x_continuous(breaks=(0,155,5)
。它有效,但直方图并未在整个屏幕上显示。
我使用 xlim(0,155)
它在整个屏幕上显示了直方图,但它覆盖了我定义的刻度。
break
获取您的主要刻度的序列列表。尝试:
scale_x_continuous(breaks=seq(0,155,5))
问题是 xlim(0, 155)
实际上是 scale_x_continuous(lim = c(0, 155))
的 shorthand。因此,当你同时使用 xlim()
和 scale_x_continuous()
时,ggplot 会混淆,只会使用 scale_x_continuous()
的两个调用之一。如果我这样做,我会收到以下警告:
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
如您所见,ggplot 仅使用您上次定义的比例。
解决方案是将限制和中断放在 scale_x_continuous()
的一次调用中。下面是一个例子,你可以运行看看它是如何工作的:
data <- data.frame(a = rnorm(1000, mean = 100, sd = 40))
ggplot(data, aes(x = a)) + geom_histogram() +
scale_x_continuous(breaks = seq(0, 155, 5), lim = c(0, 155))
让我再补充一点:中断现在与箱子宽度不太吻合,我觉得这很奇怪。所以我建议您也更改 bin 宽度。下面再次绘制直方图,但将 bin 宽度设置为 5:
ggplot(data, aes(x = a)) + geom_histogram(binwidth = 5) +
scale_x_continuous(breaks = seq(0, 155, 5), lim = c(0, 155))
以下 link 提供了很多关于如何在 ggplot 中更改轴的附加信息和示例:http://www.cookbook-r.com/Graphs/Axes_%28ggplot2%29/
我在 R 中使用 geom_histogram 构建了一个直方图,我想将我的 x 轴缩放到 155 insted of 252 显示并查看每个 5 个数字(0、5、10 等) ,我用了scale_x_continuous(breaks=(0,155,5)
。它有效,但直方图并未在整个屏幕上显示。
我使用 xlim(0,155)
它在整个屏幕上显示了直方图,但它覆盖了我定义的刻度。
break
获取您的主要刻度的序列列表。尝试:
scale_x_continuous(breaks=seq(0,155,5))
问题是 xlim(0, 155)
实际上是 scale_x_continuous(lim = c(0, 155))
的 shorthand。因此,当你同时使用 xlim()
和 scale_x_continuous()
时,ggplot 会混淆,只会使用 scale_x_continuous()
的两个调用之一。如果我这样做,我会收到以下警告:
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
如您所见,ggplot 仅使用您上次定义的比例。
解决方案是将限制和中断放在 scale_x_continuous()
的一次调用中。下面是一个例子,你可以运行看看它是如何工作的:
data <- data.frame(a = rnorm(1000, mean = 100, sd = 40))
ggplot(data, aes(x = a)) + geom_histogram() +
scale_x_continuous(breaks = seq(0, 155, 5), lim = c(0, 155))
让我再补充一点:中断现在与箱子宽度不太吻合,我觉得这很奇怪。所以我建议您也更改 bin 宽度。下面再次绘制直方图,但将 bin 宽度设置为 5:
ggplot(data, aes(x = a)) + geom_histogram(binwidth = 5) +
scale_x_continuous(breaks = seq(0, 155, 5), lim = c(0, 155))
以下 link 提供了很多关于如何在 ggplot 中更改轴的附加信息和示例:http://www.cookbook-r.com/Graphs/Axes_%28ggplot2%29/