Joe Crozier
Joe Crozier

Reputation: 1036

Purposefully unevenly space x Axis in ggplot?

Lets say I have some data kinda like the mtcars dataset (except the cyl variable is a factor in my case):

library(tidyverse)
Data<-mtcars

And lets say i want to do a graph kinda like this:

Data%>%ggplot(aes(x=as.factor(cyl),y=mpg))+geom_boxplot()

enter image description here

But lets say I wanted to just kinda stretch the x axis out like this, simply for the visual effect. And pardon my ms paint skills, it would be one continuous graph with the grid lines stretching the whole way

enter image description here

Any idea how? I don't really want to break up the graph like I assume facets would.

Upvotes: 1

Views: 593

Answers (1)

teunbrand
teunbrand

Reputation: 38063

If you convert the factor to numeric positions, you can relatively easily let the x-axis look like it is discrete.

library(tidyverse)

pos <- c(1, 5, 6)

mtcars %>% 
  mutate(cyl2 = pos[as.numeric(as.factor(cyl))]) %>%
  ggplot(aes(x = cyl2, y=mpg)) +
  geom_boxplot(aes(group = as.factor(cyl))) +
  scale_x_continuous(breaks = pos,
                     labels = levels(as.factor(mtcars$cyl))) +
  annotate("rect", xmin = 1.5, xmax  = 4.5, ymin = -Inf, ymax = Inf,
           fill = "white", colour = NA)

Upvotes: 1

Related Questions