Graphics Reference
In-Depth Information
Levels: large medium small
# Change the order of levels
sizes <- factor(sizes, levels = c( "small" , "medium" , "large" ))
sizes
small large large small medium
Levels: small medium large
The order can also be specified with levels when the factor is first created.
Discussion
There are two kinds of factors in R: ordered factors and regular factors. In both types, the levels
are arranged in someorder; the difference is that the order is meaningful for an ordered factor,
but it is arbitrary for a regular factor—it simply reflects how the data is stored. For graphing
data, the distinction between ordered and regular factors is generally unimportant, and they can
be treated the same.
The order of factor levels affects graphical output. When a factor variable is mapped to an aes-
thetic property in ggplot2, the aesthetic adopts the ordering of the factor levels. If a factor is
mapped to the x-axis, the ticks on the axis will be in the order of the factor levels, and if a factor
is mapped to color, the items in the legend will be in the order of the factor levels.
To reverse the level order, you can use rev(levels()) :
factor(sizes, levels = rev(levels(sizes)))
small large large small medium
Levels: small medium large
See Also
To reorder a factor based on the value of another variable, see Changing the Order of Factor
Levels Based on Data Values .
Reordering factor levels is useful for controlling the order of axes and legends. See Recipes and
for more information.
 
 
Search WWH ::




Custom Search