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

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".


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


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")


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


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


Updated on: 07-Nov-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started