从ggplot条形图中排除零值?

mar*_*y_c 6 r zero bar-chart ggplot2

有没有人知道是否有可能从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
Run Code Online (Sandbox Code Playgroud)

正如你在'prop'列中看到的那样,有很多零值.我正在制作一个带有"X5employf"列作为方面的刻面条形图.但由于零值,我最终在我的情节上留下了很多空白空间(见下文).有没有办法迫使ggplot不绘制零值?它不是丢弃未使用因子的情况,因为它们不是NA值而是0.有任何想法吗??!

示例情节

sc_*_*ans 5

对于您的绘图,只需使用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
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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


met*_*oia 1

我不确定是否有办法在ggplot. 不过,您可以考虑简单地将 0 重新编码为 NA:

df[df$prop == 0] <- NA
Run Code Online (Sandbox Code Playgroud)