gpt4 book ai didi

r - 限制分面图中分面的类别数

转载 作者:行者123 更新时间:2023-12-04 04:54:53 25 4
gpt4 key购买 nike

我正在使用以下方法制作 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)

最佳答案

您可以添加 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

关于r - 限制分面图中分面的类别数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com