Limiting the number of categories on facets in a facet plot

会有一股神秘感。 提交于 2019-12-12 16:50:14

问题


I'm making a facet_grid plot using the following approach:

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

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

My data is structured in the following way:

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

When I make a facet plot of this, it looks like this:

What I would like, is to limit the number of categories on each facet, so that I only show C1, C2, C3 on the first plot (etc). Is there a way that I can limit the number of categories that are shown here?


Here is the output of dput(sample) and my plot command, so that my image can be easily reproduced:

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:


You can add scales="free_x" to facet_grid(). In this case for each facet you will have x values only in range of values used for particular facet. By adding space="free_x" you can ensure that bars have the same width in all facets.

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



来源:https://stackoverflow.com/questions/16886057/limiting-the-number-of-categories-on-facets-in-a-facet-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!