person holding white Samsung Galaxy Tab

Easy methods to Exchange Line of Pieces in ggplot2 Legend

Posted on
banner 336x280

You’ll be able to usefulness please see syntax to modify the sequence of the pieces in a ggplot2 legend:

scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)

Refer to instance displays the best way to usefulness this syntax in apply.

banner 468x60

Instance: Exchange Line of Pieces in ggplot2 Legend

Assume we assemble please see plot in ggplot2 that presentations more than one boxplots in a single plot:

library(ggplot2)

#assemble knowledge body
df <- knowledge.body(staff=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 issues=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#assemble more than one boxplots to visualise issues scored via staff
ggplot(knowledge=df, aes(x=staff, y=issues, fill=staff)) +
  geom_boxplot()

To switch the sequence of the pieces within the legend, we will usefulness the scale_fill_discrete() serve as as follows:

library(ggplot2)

#assemble knowledge body
df <- knowledge.body(staff=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 issues=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#assemble more than one boxplots to visualise issues scored via staff
ggplot(knowledge=df, aes(x=staff, y=issues, fill=staff)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A'))

ggplot2 boxplot with specific order of items in legend

Understand that the sequence of the pieces modified from: A, B, C to B, C, A.

We will additionally usefulness the labels argument to modify the precise labels old for the pieces within the legend:

library(ggplot2)

#assemble knowledge body
df <- knowledge.body(staff=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 issues=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))

#assemble more than one boxplots to visualise issues scored via staff
ggplot(knowledge=df, aes(x=staff, y=issues, fill=staff)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A'),
                      labels=c('B Staff', 'C Staff', 'A Staff'))

Understand that the legend labels have modified.

Spare Assets

Refer to tutorials give an explanation for the best way to carry out alternative familiar operations in ggplot2:

Easy methods to Take away a Legend in ggplot2
Easy methods to Exchange Legend Place in ggplot2
Easy methods to Exchange Legend Measurement in ggplot2
Easy methods to Exchange the Legend Identify in ggplot2

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *