在ggplot2中刻面数据时,如何在刻度上设置不同的中断和标签?

时间:2015-07-25 20:41:37

标签: r ggplot2 facet

请考虑以下代码:

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()

它生成图像:

image plot

问题是我的scale_x_discrete()被忽略了。我希望每个方面的x比例显示data$label中的标签,但仅限于有数据的地方。换句话说,我想要这样的东西,但在一张图表上:

facet

facet

facet

我该怎么做?

2 个答案:

答案 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)

enter image description here

答案 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()

enter image description here

使用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()

enter image description here

ggplot(data, aes(x = label, y = type)) +
  labs(x = "", y = "") +
  theme_bw() +
  facet_wrap(~ type, ncol = 1, scales = "free") +
  geom_point()

enter image description here