在不定义顺序的情况下更改轴断裂-ggplot [英] Change axis breaks without defining sequence - ggplot

查看:100
本文介绍了在不定义顺序的情况下更改轴断裂-ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在ggplot中设置中断步长,而无需定义序列.例如:

Is there any way to set the break step size in ggplot without defining a sequence. For example:

x <- 1:10
y <- 1:10

df <- data.frame(x, y)

# Plot with auto scale
ggplot(df, aes(x,y)) + geom_point()

# Plot with breaks defined by sequence
ggplot(df, aes(x,y)) + geom_point() +
  scale_y_continuous(breaks = seq(0,10,1))

# Plot with automatic sequence for breaks
ggplot(df, aes(x,y)) + geom_point() +
  scale_y_continuous(breaks = seq(min(df$y),max(df$y),1))

# Does this exist?
ggplot(df, aes(x,y)) + geom_point() +
  scale_y_continuous(break_step = 1)

您可能会说我很懒,但是由于添加了误差线,在某些情况下我不得不更改seqminmax限制.所以我只想说...使用x的间隔大小,并具有自动缩放限制.

You may say I am being lazy but there have been a few occasions where I have had to change the min and max limits of my seq due to the addition of error bars. So I just want to say...use a break size of x, with automatic scale limits.

推荐答案

您可以定义自己的函数以传递给breaks参数.

You can define your own function to pass to the breaks argument. An example that would work in your case would be

f <- function(y) seq(floor(min(y)), ceiling(max(y)))

然后

ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f)

给予

您可以修改此设置以通过中断步骤,例如

You could modify this to pass the step of the breaks, e.g.

f <- function(k) {
        step <- k
        function(y) seq(floor(min(y)), ceiling(max(y)), by = step)       
}

然后

ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f(2))

将创建一个带有2、4,..,10等刻度的y轴.

would create a y-axis with ticks at 2, 4, .., 10, etc.

您可以通过编写自己的缩放功能来进一步扩展

You can take this even further by writing your own scale function

my_scale <- function(step = 1, ...) scale_y_continuous(breaks = f(step), ...)

然后像

ggplot(df, aes(x,y)) + geom_point() + my_scale()

这篇关于在不定义顺序的情况下更改轴断裂-ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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