Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set different breaks and labels on the scales when facetting data in ggplot2?

Tags:

r

ggplot2

facet

Consider the following code:

library(ggplot2)    
data = data.frame(x = c(1, 2,
                        3, 4,
                        5, 6),
                  label = c("foo", "bar",
                            "bar", "baz",
                            "baz", "boo"),
                  type = c(1, 1,
                           2, 2,
                           3, 3))
ggplot(data, aes(x = x, y = c(1))) +
    labs(x = "", y = "") +
    theme_bw() +
    facet_wrap(~ type, ncol = 1, scales = "free_x") +
    scale_x_discrete(aes(breaks = x, labels=label), limits = 1:6) +
    geom_point()

It generates the image:

image plot

The problem is that my scale_x_discrete() is ignored. I would like each facet's x scale to show the labels in data$label, but only where there is data. In other words, I would like something like this, but on a single chart:

facet

facet

facet

How can I do it?

like image 760
Vitor Baptista Avatar asked Jul 25 '15 20:07

Vitor Baptista


1 Answers

You might need to construct the plots separately, then combine them using grid.arrange:

library(ggplot2)    
data = data.frame(x = c(1, 2,
                        3, 4,
                        5, 6),
                  label = c("foo", "bar",
                            "bar", "baz",
                            "baz", "boo"),
                  type = c(1, 1,
                           2, 2,
                           3, 3))

library(gridExtra)  # Using V 2.0.0

p = list()

for(i in 1:3) {

df = subset(data, type == i)

p[[i]] = ggplot(df, aes(x = x, y = c(1)) ) +
    labs(x = "", y = "") +
    theme_bw() +
    expand_limits(x = c(1, 6)) + 
    facet_wrap(~ type, ncol = 1) +
    scale_x_continuous(breaks = df$x, labels = df$label) +
    geom_point()
   }

grid.arrange(grobs = p, ncol = 1)

enter image description here

like image 159
Sandy Muspratt Avatar answered Sep 30 '22 18:09

Sandy Muspratt