Change axis breaks without defining sequence - ggplot

前端 未结 1 1059
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 18:46

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          


        
相关标签:
1条回答
  • 2020-12-31 19:28

    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)))
    

    Then

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

    gives

    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)       
    }
    

    then

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

    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), ...)
    

    and just call it like

    ggplot(df, aes(x,y)) + geom_point() + my_scale()
    
    0 讨论(0)
提交回复
热议问题