Add legend entries for stacked bar chart

56 views
Skip to first unread message

thomas kern

unread,
Sep 11, 2012, 2:43:25 AM9/11/12
to ggp...@googlegroups.com
Hi,

is there a way to get legend entries into a legend produced by a stacked bar chart?

data = data.frame(x=c(1,2,3,2,2))
ggplot(data,aes(x=1,fill=factor(x))) + geom_bar(position="stack")

how would I add 4, 5 and 6 to the legend?

thank you very much,
thomas

Brian Diggs

unread,
Sep 11, 2012, 10:48:23 AM9/11/12
to thomas kern, ggplot2
On 9/10/2012 11:43 PM, thomas kern wrote:
> Hi,
>
> is there a way to get legend entries into a legend produced by a stacked
> bar chart?
>
> data = data.frame(x=c(1,2,3,2,2))
> ggplot(data,aes(x=1,fill=factor(x))) + geom_bar(position="stack")
>
> how would I add 4, 5 and 6 to the legend?

The most straightforward way is to make x in data be a factor with all
the possible levels (1 through 6). Then you just need a
scale_fill_discrete call to include all levels.

data = data.frame(x=factor(c(1,2,3,2,2), levels=1:6))
ggplot(data,aes(x=1,fill=x)) +
geom_bar(position="stack") +
scale_fill_discrete(drop=FALSE)



> thank you very much,
> thomas
>


--
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University

Thomas Kern

unread,
Sep 11, 2012, 12:38:53 PM9/11/12
to Brian Diggs, thomas kern, ggplot2
weird. I tried this but apparently the wrong way as your solution works.

thank you.

-- thomas
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
Reply all
Reply to author
Forward
0 new messages