2

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
user20650
  • 24,654
  • 5
  • 56
  • 91
wesanyer
  • 982
  • 1
  • 6
  • 27
  • I'm not sure I understand your question. The x-axis labels already show the contents of "rank" column. The legend shows the contents of the "names" column. As you can see, there are only a handful of items (the top three) which vary between the two. These are the only ones I want to appear on the legend. – wesanyer Aug 21 '15 at 13:40

1 Answers1

5

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"))

enter image description here

Heroka
  • 12,889
  • 1
  • 28
  • 38