![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Advertisements