How to drop unused categories in x axis?

library(ggplot2)
library(lemon)
df <- data.frame(
  v1 = c("A", "A", "A", "B", "B", "B"),
  v2 = c("S1", "S2", "S3", "S7", "S8", "S9"),
  nm = c(2, 3, 4, 5, 6, 7)
)

ggplot(df, aes(x = v2, y = nm)) +
  geom_point(size = 3) +
facet_grid(v1~., scales = "free_x")

Or using lemon package with `facet_rep_grid(v1~., scales = "free_x", repeat.tick.labels = T)`

Just off the top of my head, don't use faceting. Split the data into two data.frames, plot separately and use something like {patchwork} or {cowplot} to arrange the two plots.

suppressMessages(library(tidyverse))
library(patchwork)
dat1 <- data.frame(
  v1 = c("A", "A", "A", "B", "B", "B"),
  v2 = c("S1", "S2", "S3", "S7", "S8", "S9"),
  nm = c(2, 3, 4, 5, 6, 7)
)

AA  <- subset(dat1, v1 == "A")
BB <- subset(dat1, v1 == "B")

p1  <- ggplot(AA, aes(x = v2, y = nm)) +
  geom_point(size = 3) + ylim(2, 7)

p2  <- ggplot(BB, aes(x = v2, y = nm)) +
  geom_point(size = 3) + ylim(2, 7)

p1 / p2
 ## or
p1 + p2

It works fine with facet_wrap:

ggplot(df, aes(x = v2, y = nm)) +
  geom_point(size = 3) +
  facet_wrap(~v1, scales = "free_x", ncol = 1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.