How to set the legends using ggplot2 on top-right side in R?

R ProgrammingServer Side ProgrammingProgramming

The default position of legend in a plot created by using ggplot2 is right hand side but we can change the position by using theme function that has legend.position argument and legend.justification argument. To set the legend on top-right side we can use legend.position="top" and legend.justification="right".

Example

Consider the below data frame:

Consider the below data frame:

Live Demo

> x<-c("Mango","Guava","Pomegranate")
> freq<-c(212,220,218)
> df<-data.frame(x,freq)
> df

Output

x freq
1 Mango 212
2 Guava 220
3 Pomegranate 218

Loading ggplot2 package and creating bar chart with legend:

> library(ggplot2)
> ggplot(df,aes(x,freq,fill=x))+geom_bar(stat="identity")

Output:

Creating the bar chart with legend on top-right hand side of the chart:

Example

> ggplot(df,aes(x,freq,fill=x))+geom_bar(stat="identity")+theme(legend.position="top",legend.justification="right")

Output:

raja
Published on 07-Nov-2020 12:02:26
Advertisements