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

Vit*_*sta 6 r facet ggplot2

请考虑以下代码:

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()
Run Code Online (Sandbox Code Playgroud)

它生成图像:

图像情节

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

面

面

面

我该怎么做?

San*_*att 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述