person holding white Samsung Galaxy Tab

The way to Exchange Legend Labels in ggplot2 (With Examples)

Posted on
banner 336x280

You’ll utility please see syntax to modify the legend labels in ggplot2:

p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

Please see instance displays utility this syntax in follow.

banner 468x60

Instance: Exchange Legend Labels in ggplot2

Assume we form please see grouped boxplot in ggplot2:

library(ggplot2) 

#put together this situation reproducible
eager.seed(1)

#form dataset
information <- information.body(staff=rep(c('A', 'B', 'C'), each and every=50),
                   program=rep(c('low', 'prime'), each and every=25),
                   values=seq(1:150)+pattern(1:100, 150, exchange=TRUE))

#form grouped boxplots
p <- ggplot(information, aes(x=staff, y=values, fill=program)) + 
       geom_boxplot() 

#show grouped boxplots
p

Through default, the legend labels tackle please see values for the fill variable:

On the other hand, assume we’d like to modify the legend labels to:

We will utility please see syntax to take action:

#form grouped boxplots with customized legend labels
p <- ggplot(information, aes(x=staff, y=values, fill=program)) + 
       geom_boxplot() +
       scale_fill_discrete(labels=c('Top Program', 'Low Program'))

#show grouped boxplots
p

The legend now shows the labels that we specified.

Backup Assets

Please see tutorials provide an explanation for carry out alternative regular duties in ggplot2:

The way to Exchange the Legend Identify in ggplot2
The way to Exchange Legend Place in ggplot2
The way to Exchange Legend Measurement in ggplot2
The way to Take away a Legend in ggplot2

banner 336x280

Leave a Reply

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