
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Scatterplot in R with Legend Inside Plot Area Using ggplot2
Legends help us to differentiate the values of the response variable while creating the scatterplot. In this way, we can understand how one level of a factor variable affects the response variable. The legend is preferred to be positioned at left bottom, top right, top left, and bottom right. We can use theme function to position the legends.
Example
Consider the below data frame −
> set.seed(99) > x1<-rnorm(20) > x2<-rnorm(20,2) > F<-factor(c("A","B","C","D")) > df<-data.frame(x1,x2,F) > library(ggplot2)
Creating the plot with different legend positions −
Consider the below data frame −
> ggplot(df, aes(x=x1, y=x2, colour=F)) + geom_point(aes(colour=F)) + + theme(legend.justification = c(1, 0), legend.position = c(1, 0))
Output
> ggplot(df, aes(x=x1, y=x2, colour=F)) + geom_point(aes(colour=F)) + + theme(legend.justification = c(1, 1), legend.position = c(1, 1))
Output
> ggplot(df, aes(x=x1, y=x2, colour=F)) + geom_point(aes(colour=F)) + + theme(legend.justification = c(0, 1), legend.position = c(0, 1))
Output
> ggplot(df, aes(x=x1, y=x2, colour=F)) + geom_point(aes(colour=F)) + + theme(legend.justification = c(0, 0), legend.position = c(0, 0))
Output
Advertisements