Reputation: 2096
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?
Upvotes: 7
Views: 4398
Reputation: 32859
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)
Upvotes: 3
Reputation: 13580
Changing the argument to scales = "free"
. I modified the example adding 'y = type` instead of the constant c(1) to get different scales.
ggplot(data, aes(x = x, y = type)) +
labs(x = "", y = "") +
theme_bw() +
facet_wrap(~ type, ncol = 1, scales = "free") +
scale_x_discrete(aes(breaks = x), labels = data$label, limits = 1:6) +
geom_point()
Using scales = "free_y"
ggplot(data, aes(x = x, y = type)) +
labs(x = "", y = "") +
theme_bw() +
facet_wrap(~ type, ncol = 1, scales = "free_y") +
scale_x_discrete(aes(breaks = x), labels = data$label, limits = 1:6) +
geom_point()
ggplot(data, aes(x = label, y = type)) +
labs(x = "", y = "") +
theme_bw() +
facet_wrap(~ type, ncol = 1, scales = "free") +
geom_point()
Upvotes: 2