Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

10. Legends > Changing the Order of Items in a Legend

Changing the Order of Items in a Legend

Problem

You want to change the order of the items in a legend.

Solution

Set the limits in the scale to the desired order (Figure 10-5):

# The base plot
p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
p

# Change the order of items
p + scale_fill_discrete(limits=c("trt1", "trt2", "ctrl"))
Left: default order for legend; right: modified
            order
Figure 10-5. Left: default order for legend; right: modified order

Discussion

Note that the order of the items on the x-axis did not change. To do that, you would have to set the limits of scale_x_discrete() (Changing the Order of Items on a Categorical Axis), or change the data to have a different factor level order (Changing the Order of Factor Levels).


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint