限制构面图中构面的类别数量

时间:2013-06-02 18:43:20

标签: r plot ggplot2 facets

我正在使用以下方法制作facet_grid图:

sample <- read.csv('sample.csv')

ggplot(sample, aes(category, count)) + geom_bar() + facet_grid(. ~ parent_id)

我的数据按以下方式构建:

id,parent_id, category, count
1,          21,     C1,       4
2,          21,     C2,       7
3,          21,     C3,       4
4,          22,     D1,      28
5,          22,     D2,      20
6,          22,     D3,       0
7,          22,     D5,       1
8,          22,     D6,       4
9,          22,     D7,       1
10,         23,     E1,      17
11,         23,     E2,      33
12,         23,     E3,      31

当我对此进行剖面图时,它看起来像这样:

enter image description here

我想要的是限制每个方面的类别数量,以便我只在第一个方块(等)上显示C1, C2, C3。有没有办法可以限制此处显示的类别数量?


以下是dput(sample)和我的情节命令的输出,以便我的图像可以轻松复制:

sample <-  

structure(list(id = 1:12, parent_id = c(21L, 21L, 21L, 22L, 22L, 
22L, 22L, 22L, 22L, 23L, 23L, 23L), category = structure(1:12, .Label = c("     C1", 
"     C2", "     C3", "     D1", "     D2", "     D3", "     D5", 
"     D6", "     D7", "     E1", "     E2", "     E3"), class = "factor"), 
    count = c(4L, 7L, 4L, 28L, 20L, 0L, 1L, 4L, 1L, 17L, 33L, 
    31L)), .Names = c("id", "parent_id", "category", "count"), class = "data.frame", row.names = c(NA, 
-12L))

 ggplot(sample, aes(category, count)) + geom_bar() + facet_grid(. ~ parent_id)

1 个答案:

答案 0 :(得分:3)

您可以将scales="free_x"添加到facet_grid()。在这种情况下,对于每个构面,只有在用于特定构面的值范围内才有x值。通过添加space="free_x",您可以确保条形在所有方面具有相同的宽度。

ggplot(sample, aes(category, count)) + geom_bar() + 
  facet_grid(. ~ parent_id,scale="free_x",space="free_x")

enter image description here