请考虑以下代码:
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()
它生成图像:
问题是我的scale_x_discrete()
被忽略了。我希望每个方面的x比例显示data$label
中的标签,但仅限于有数据的地方。换句话说,我想要这样的东西,但在一张图表上:
我该怎么做?
答案 0 :(得分:3)
您可能需要单独构建图表,然后使用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)
答案 1 :(得分:2)
将参数更改为scales = "free"
。我修改了添加'y = type`而不是常量c(1)的示例来获得不同的比例。
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()
使用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()