首页 > 解决方案 > ggplot 和 geom_text() 标签

问题描述

我是 R 和 ggplot2 的新手。我在这里使用了很多很好的例子,但仍然找不到解决方案。我的数据框如下所示:

   Thermal.sensation           Acceptance Votes
1                 -3   Clearly acceptable  0.00
2                 -3      Just acceptable  0.33
3                 -3    Just unacceptable  0.53
4                 -3 Clearly unacceptable  0.13
5                 -2   Clearly acceptable  0.05
6                 -2      Just acceptable  0.80
7                 -2    Just unacceptable  0.15
8                 -2 Clearly unacceptable  0.00
9                 -1   Clearly acceptable  0.25
10                -1      Just acceptable  0.73
11                -1    Just unacceptable  0.02
12                -1 Clearly unacceptable  0.00
13                 0   Clearly acceptable  0.06
14                 0      Just acceptable  0.90
15                 0    Just unacceptable  0.03
16                 0 Clearly unacceptable  0.00
17                 1   Clearly acceptable  0.00
18                 1      Just acceptable  0.63
19                 1    Just unacceptable  0.38
20                 1 Clearly unacceptable  0.00
21                 2   Clearly acceptable  0.00
22                 2      Just acceptable  0.00
23                 2    Just unacceptable  1.00
24                 2 Clearly unacceptable  0.00
25                 3   Clearly acceptable  0.00
26                 3      Just acceptable  0.00
27                 3    Just unacceptable  0.00
28                 3 Clearly unacceptable  0.00

并且当打印绘图时,每列中都会出现每个零值。我想知道如何隐藏或使情节中的那些零不可见。

问题参考图片

这是我用来制作情节的代码。

dfQ3 <- data.frame(Thermal.sensation,Acceptance,Votes)
dfQ3$Thermal.sensation <- factor(dfQ3$Thermal.sensation, 
                                 levels = c(-3,-2,-1,0,+1,+2,+3))
dfQ3$Acceptance <- factor(dfQ3$Acceptance, 
                          levels = c("Clearly acceptable","Just acceptable",
                                     "Just unacceptable","Clearly unacceptable"))
p3 <- ggplot(dfQ3, 
             aes(fill=Acceptance, y=Votes, x=Thermal.sensation)) + 
  geom_bar(position="fill", stat="identity") +
  scale_fill_brewer(palette = "Blues", direction = -1) +
  geom_text(aes(label=Votes),
            position = position_stack(vjust = 0.5))

标签: rggplot2

解决方案


您可以将data=参数设置为geom_text()专门排除任何零值。一种方法是使用subset(),因此geom_text您的代码行可以更改为如下所示:

geom_text(data=subset(dfQ3, Votes!=0), aes(label=Votes),position = position_stack(vjust = 0.5))

给你下面的情节(注意我必须添加下划线以便更容易导入你的数据):

在此处输入图像描述


推荐阅读