- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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:
- Related Articles
- How to increase the space between horizontal legends using ggplot2 in R?
- How to display legend on top using ggplot2 in R?
- How to set the position of legend of a ggplot2 graph to left-top side in R?
- How to create a scatterplot with two legends using ggplot2 in R?
- How to display tick marks on upper as well as right side of the plot using ggplot2 in R?
- Count smaller elements on right side using Set in C++ STL
- How to X-axis labels to the top of the plot using ggplot2 in R?
- How to set the Y-axis tick marks using ggplot2 in R?
- How to create a bar plot in R with label of bars on top of the bars using ggplot2?
- How to set the chart title at the bottom using ggplot2 in R?
- How to display the curve on the histogram using ggplot2 in R?
- How to manage top and bottom spaces of a bar plot using ggplot2 in R?
- How to set the X-axis labels in histogram using ggplot2 at the center in R?
- How to color scatterplot points based on a threshold using ggplot2 in R?
- How to change the tick size using ggplot2 in R?

Advertisements