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