- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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".
Example
Consider the below data frame:
Consider the below data frame:
> 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:
Advertisements
To Continue Learning Please Login
Login with Google