4

I have a plot with a discrete x-axis and I want to tweak the extra space on both sides of the scale, making it smaller on the left and bigger on the right, so the long labels will fit. scale_x_discrete(expand=c(0, 1)) is not my friend here, as it always works on both side simultaneously. This question is similar but addresses continuous scales.

How can I achieve that?

set.seed(0)
L <- sapply(LETTERS, function(x) paste0(rep(x, 10), collapse=""))
x <- data.frame(label=L[1:24], 
                g2 = c("a", "b"),
                y = rnorm(24))
x$g2 <- as.factor(x$g2)
x$xpos2 <- as.numeric(x$g2) + .25

# two groups
ggplot(x, aes(x=g2, y=y)) + 
  geom_boxplot(width=.4) +
  geom_point(col="blue") +
  geom_text(aes(x=xpos2, label=label, hjust=0)) 

enter image description here

Community
  • 1
  • 1
Mark Heckmann
  • 10,943
  • 4
  • 56
  • 88

1 Answers1

7

This may be what you're looking for:

library(ggplot2)
set.seed(0)
L <- sapply(LETTERS, function(x) paste0(rep(x, 10), collapse=""))
x <- data.frame(label=L[1:24], 
                g2 = c("a", "b"),
                y = rnorm(24))
x$g2 <- factor(x$g2, levels=c("a", "b", "c"))
x$xpos2 <- as.numeric(x$g2) + .25


# two groups
ggplot(x, aes(x=g2, y=y)) + 
  geom_boxplot(width=.4) +
  geom_point(col="blue") +
  geom_text(aes(x=xpos2, label=label, hjust=0)) +
  scale_x_discrete(expand=c(0.1,0),
                   breaks=c("a", "b"),
                   labels=c("a", "b"),
                   limits=c("a", "b", "c"), drop=FALSE)

enter image description here

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205