- 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 a scatterplot in R with legend position inside the 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
- Related Articles
- How to create a scatterplot with two legends using ggplot2 in R?
- How to create a scatterplot with dark points using ggplot2 in R?
- How to create a scatterplot in R using ggplot2 with transparency of points?
- How to create horizontal legend using ggplot2 in R?
- How to create scatterplot with intercept equals to 1 using ggplot2 in R?
- How to create a scatterplot in R using ggplot2 with different designs of points?
- How to create a scatterplot with low intensity of points using ggplot2 in R?
- How to put the plot title inside the plot using ggplot2 in R?
- How to plot means inside boxplot using ggplot2 in R?
- How to create a bar plot with ggplot2 using stat_summary in R?
- How to create scatterplot using ggplot2 without grey background in R?
- How to create a scatterplot with white background and no gridlines using ggplot2 in R?
- How to create stacked plot with density using ggplot2 in R?
- How to create scatterplot for categories with grey color palette using ggplot2 in R?
- How to create a dot plot using ggplot2 in R?

Advertisements