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:
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:
How can I do it?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With