如何缩放X轴并在R中添加刻度 [英] How to scale x axis and add ticks in R

查看:228
本文介绍了如何缩放X轴并在R中添加刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用geom_histogram在R中构建直方图,我想将我的x轴缩放到显示的252的155 insted,并查看刻度5个数字(0、5、10等),我使用了.它起作用了,但直方图并未在整个屏幕上显示. 我使用了xlim(0,155),它在整个屏幕上都显示了直方图,但是它覆盖了我定义的刻度.

I build an Histogram in R using geom_histogram, I want to scale my x axis up to 155 insted of 252 that is showing and to see a tick evrey 5 numbers (0,5,10 etc), I used the scale_x_continuous(breaks=(0,155,5). it worked but the histogram is not presented all across the screen. I used xlim(0,155) it showed the histogram all across the screen but it override the ticks I defined.

推荐答案

问题是xlim(0, 155)实际上是scale_x_continuous(lim = c(0, 155))的简写.因此,当同时使用xlim()scale_x_continuous()时,ggplot会感到困惑,并且只会使用scale_x_continuous()的两个调用之一.如果执行此操作,则会收到以下警告:

The problem is that xlim(0, 155) is actually a shorthand for scale_x_continuous(lim = c(0, 155)). Therefore, when you use both, xlim() and scale_x_continuous(), ggplot is confused and will only use one of the two calls of scale_x_continuous(). If I do this, I get the following warning:

"x"的比例已经存在.为"x"添加另一个比例,它将替换现有比例.

Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

如您所见,ggplot仅使用您最后定义的比例.

As you can see, ggplot is only using the scale that you defined last.

解决方案是将限制和破损放入scale_x_continuous()的一个调用中.以下是您可以运行以查看其工作方式的示例:

The solution is to put the limits and the breaks into one call of scale_x_continuous(). The following is an example that you can run to see how it works:

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宽度设置为5:

Let me add another remark: The breaks do now not fit well with the bin width, which I find rather odd. So I would suggest that you also change the bin width. The following plots the histogram again, but sets the bin width to 5:

ggplot(data, aes(x = a)) + geom_histogram(binwidth = 5) +
    scale_x_continuous(breaks = seq(0, 155, 5), lim = c(0, 155))

以下链接提供了有关如何更改ggplot中轴的许多其他信息和示例: http://www.cookbook-r.com/Graphs/Axes_%28ggplot2%29/

The following link provides a lot of additional information and examples on how to change axes in ggplot: http://www.cookbook-r.com/Graphs/Axes_%28ggplot2%29/

这篇关于如何缩放X轴并在R中添加刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆