gpt4 book ai didi

r - 从ggplot条形图中排除零值?

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

有谁知道是否可以从 ggplot 的条形图中排除零值?

我有一个包含以下比例的数据集:

 X5employf       prop X5employff
1 increase 0.02272727
2 increase 0.59090909 1
3 increase 0.02272727 1 and 8
4 increase 0.02272727 2
5 increase 0.34090909 3
6 increase 0.00000000 4
7 increase 0.00000000 5
8 increase 0.00000000 6
9 increase 0.00000000 6 and 7
10 increase 0.00000000 6 and 7
11 increase 0.00000000 7
12 increase 0.00000000 8
13 decrease 0.00000000
14 decrease 0.00000000 1
15 decrease 0.00000000 1 and 8
16 decrease 0.00000000 2
17 decrease 0.00000000 3
18 decrease 0.10000000 4
19 decrease 0.50000000 5
20 decrease 0.20000000 6
21 decrease 0.00000000 6 and 7
22 decrease 0.00000000 6 and 7
23 decrease 0.10000000 7
24 decrease 0.10000000 8
25 same 0.00000000
26 same 0.00000000 1
27 same 0.00000000 1 and 8
28 same 0.00000000 2
29 same 0.00000000 3
30 same 0.21052632 4
31 same 0.31578947 5
32 same 0.26315789 6
33 same 0.15789474 6 and 7
34 same 0.00000000 6 and 7
35 same 0.05263158 7
36 same 0.00000000 8

正如您在“ Prop ”列中看到的那样,有很多零值。我正在生成一个以“X5employf”列作为分面的分面条形图。但是由于零值,我最终在我的情节上有很多空白空间(见下文)。有没有办法强制 ggplot 不绘制零值?它不是丢弃未使用的因子的情况,因为这些不是 NA 值而是 0。有任何想法吗??!

example plot

最佳答案

对于您的情节,只需使用 which指定您只想使用包含非零比例的数据帧的子集。这样您就不必修改原始数据框。然后,在您的 scales 中指定“free_x”内部参数 facet_grid摆脱你的多面情节中的空白空间。

plot <- ggplot(df[which(df$prop>0),], aes(X5employff, prop)) +
geom_bar(aes(fill=X5employff, stat="identity")) +
facet_grid( ~ X5employf, scales="free_x") +
theme_bw()
plot

enter image description here

请注意,为了从 Excel 快速导入到 R,我将空白字段替换为“空白”。

关于r - 从ggplot条形图中排除零值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17896266/

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