- Trending Categories
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 create horizontal legend using ggplot2 in R?
The default legend direction is vertical but it can be changed to horizontal as well and for this purpose we can use legend.direction argument of theme function of ggplot2 package. For example, if we want to create a bar chart with x as categories and y as frequencies tjat are contained in a data frame df then the bar chart with horizontal legends for categories in x can be created as −
ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+theme(legend.direction="horizontal")
Example
Consider the below data frame −
> x<-c("A","B","C") > y<-c(27,25,28) > df<-data.frame(x,y) > df
Output
x y 1 A 27 2 B 25 3 C 28
Loading ggplot2 package and creating the bar chart −
Example
> library(ggplot2) > ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")
Output
Creating the chart with horizontal legend −
Example
> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+theme(legend.direction="horizontal")
Output
- Related Articles
- How to create colored barplot using ggplot2 without legend entries in R?
- How to create a horizontal bar graph using ggplot2 in R?
- How to change the legend shape using ggplot2 in R?
- How to display legend on top using ggplot2 in R?
- How to create facetted plot with facets in horizontal direction using ggplot2 in R?
- How to cover legend in a box using ggplot2 in R?
- How to change legend for multiple histograms using ggplot2 in R?
- How to create a scatterplot in R with legend position inside the plot area using ggplot2?
- How to create a dashed horizontal line in a ggplot2 graph in R?
- How to change the legend title in ggplot2 in R?
- How to create a bar graph using ggplot2 without horizontal gridlines and Y-axes labels in R?
- How to increase the space between horizontal legends using ggplot2 in R?
- How to create a horizontal line in ggplot2 graph with larger width in R?
- How to create a horizontal line in ggplot2 graph with different color in R?
- Remove grey color from legend display using ggplot2 in R.

Advertisements