1

The ggplot function expand_limits(x = 0) produces very pleasing spacing for many graphs (in a loop) but I'd rather not have the zero label. Does anyone know how to remove the zero label only ? The labels also need to be integer so I've tried to modify Joshua Cook's function:

integer_breaks <- function(n = 5, ...) {
fxn <- function(x) {
breaks <- floor(pretty(x, n, ...))
names(breaks) <- attr(breaks, "labels")
breaks
}
return(fxn)
}

to no avail. A minimal example is:

xxx <- c(1, 2, 4, 1, 1, 4, 2, 4, 1, 1, 3,  3, 4 )
yyy <- c(11, 22, 64, 45, 76, 47, 23, 44, 65, 86, 87, 83, 56 ) 
data <- data.frame(xxx, yyy) 
p <- ggplot(data = data, aes(x = data[ , 1], y = data[ , 2]), group = data[ , 1]) + geom_count(color = "blue") + expand_limits(x = 0) + scale_x_continuous(breaks = integer_breaks()) 
p 

I don't want the zero on the x-axis but I don't know in advance how many other x-axis values there will be. An alternative would be to produce a space on the left-hand side of the graph in a similar way to that given by expand limits - but the width of this would have to relate to the number of x-axis values.

1 Answer 1

1

Here is one potential solution:

library(tidyverse)

int_breaks_drop_zero <- function(n = 5, ...) {
  fxn <- function(x) {
    breaks <- floor(pretty(x, n, min.n = 0, ...))
    names(breaks) <- attr(breaks, "labels")
    breaks[breaks != 0]
  }
  return(fxn)
}

xxx <- c(1, 2, 3, 1, 1, 3, 2, 3, 1, 1, 3,  3, 3)
yyy <- c(11, 22, 64, 45, 76, 47, 23, 44, 65, 86, 87, 83, 56 ) 
data <- data.frame(xxx, yyy) 
p <- ggplot(data = data, aes(x = data[ , 1], y = data[ , 2]), group = data[ , 1]) +
  geom_count(color = "blue") +
  expand_limits(x = 0) +
  scale_x_continuous(breaks = int_breaks_drop_zero())
p

Created on 2024-03-13 with reprex v2.1.0

Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks - so far so good. This is exactly what I want for the minimal example and others with 5 or more breaks. Unfortunately, I have other examples with only 3 breaks with 0, 1 and 2 - and for these the 0s remain. I'm also not at all sure what the n = 5 does in the function - I can delete n but 0,1,2 still gives a zero. If I change it to n = 2 it removes previously good numbers from those with more breaks. Any ideas how to extend this success to any numbers of breaks ?
Yes - that's it ! It could be noted that, for ordinal data, this solution is important because the zeros have no meaning here. Thanks.
Oh! I was wondering why you would want to do this - ordinal data makes sense! Glad you solved your problem @Abiologist :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.