Removing Labels from Legend in ggplot2

瘦欲@ 提交于 2019-12-11 03:12:26

问题


I have the data frame below that I have graphed as shown. How can I limit the values shown in the legend to only the first three? In other words, I want it to only show "A", "B", and "C".

graph_table <- read.table(header=TRUE, text="
   names freq  rank percs sums sums_str
1      A 1208 'Top 3'  46.1 61.1    61.1%
2      B  289 'Top 3'  11.0 61.1    61.1%
3      C  105 'Top 3'   4.0 61.1    61.1%
4      D  388     D  14.8 14.8    14.8%
5      E  173     E   6.6  6.6     6.6%
6      F  102     F   3.9  3.9     3.9%
7      G   70     G   2.7  2.7     2.7%
8      H   54     H   2.1  2.1     2.1%
9      I   44     I   1.7  1.7     1.7%
10     J   32     J   1.2  1.2     1.2%
11     K   24     K   0.9  0.9     0.9%
12     L   20     L   0.8  0.8     0.8%
13     M   20     M   0.8  0.8     0.8%
14     N   18     N   0.7  0.7     0.7%
15     O   13     O   0.5  0.5     0.5%
16     P   10     P   0.4  0.4     0.4%
17     Q   10     Q   0.4  0.4     0.4%
18     R   10     R   0.4  0.4     0.4%
19     S    7     S   0.3  0.3     0.3%
20     T    5     T   0.2  0.2     0.2%
21     U    5     U   0.2  0.2     0.2%
22     V    5     V   0.2  0.2     0.2%
23     W    3     W   0.1  0.1     0.1%")

library(ggplot2) 

p <- ggplot(graph_table[1:10,], aes(x=rank, y=percs,   
            fill=names))+geom_bar(stat="identity")
p <- p+geom_text(aes(label=sums_str, y=(sums+4)), size=4)
p

回答1:


Was confused at first, but you want to show a top-3 so the other names don't need a legend. Here you go:

p <- ggplot(graph_table[1:10,], aes(x=rank, y=percs,   
                                    fill=names))+geom_bar(stat="identity")
p <- p+geom_text(aes(label=sums_str, y=(sums+4)), size=4)
p + scale_fill_discrete(breaks=c("A","B","C"))



来源:https://stackoverflow.com/questions/32141583/removing-labels-from-legend-in-ggplot2

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