ordering of scale colours to match order of bars in histogram

15 views
Skip to first unread message

Ivan Alves

unread,
Apr 3, 2009, 10:40:17 AM4/3/09
to ggplot2
Dear all,
For the histograms (geom_bar filled with a categorical variable) the
colour legend is ranked in the opposite order of the histogram, making
the reading of the chart a bit complicated (see for example the right
hand side of figures 4.6 and 2.12 of Hadley's book - 24 February
version). Could they not be ordered in the same way?
Kind regards,
Ivan

James Howison

unread,
Apr 3, 2009, 5:48:54 PM4/3/09
to ggplot2
Does that happen if you order the categorical variables?

Could you provide a complete minimal example and confirm the version
of ggplot2 that you are using?

--J

Bob Pap

unread,
Apr 4, 2009, 3:43:19 AM4/4/09
to James Howison, ggplot2
I am using version 0.8.2.  The examples of the book are pretty clear (see the code for Figure 2.12 below).  The issue is not one of ordering of the factors, but rather of the matching between the stacks in the plot (from top to down) and those of the legend (also from top to down).  ggplot stacks the histogram starting from the bottom (in the order of the factors) and the legends stacks them from the top (also in the order of the factors), resulting in an "inverse ordering" of stacks.

qplot(carat, data = diamonds, geom = "histogram", fill = color)

hadley wickham

unread,
Apr 4, 2009, 9:58:18 AM4/4/09
to Bob Pap, James Howison, ggplot2
Hi Bob,

You can work around this by manually specifying the ordering of the
breaks in the legend:

+ scale_colour_hue(breaks = rev(levels(diamonds$color)))

I did used to have the legends in the opposite order to alleviate just
this problem, but it hurts in more cases than it helps.

Hadley
--
http://had.co.nz/

Bob Pap

unread,
Apr 5, 2009, 5:51:14 PM4/5/09
to hadley wickham, James Howison, ggplot2
Hi Hadley, many thanks for the guidance.  however, I try your suggestion reversing the order of the factors with the example cited and I get exactly the same.  What am I doing wrong? (the colours in the histograms go - from top to bottom - from lila to red and those of the legends from red to lila)

> qplot(carat, data = diamonds, geom = "histogram", fill = color)
> qplot(carat, data = diamonds, geom = "histogram", fill = color)+ scale_colour_hue(breaks = rev(levels(diamonds$color)))
Reply all
Reply to author
Forward
0 new messages