
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to create two lines using ggplot2 based on a categorical column in R?
To create two lines using ggplot2 based on a categorical column in R, we can follow the below steps −
- First of all, create a data frame.
- Then, create the line chart with categorical column read as factor inside aes of ggplot function.
Create the data frame
Let's create a data frame as shown below −
x<-rpois(10,5) y<-rpois(10,2) factor<-sample(0:1,10,replace=TRUE) df<-data.frame(x,y,factor) df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y factor 1 3 2 0 2 7 1 1 3 3 3 0 4 3 3 1 5 6 2 1 6 5 2 1 7 5 3 0 8 4 5 1 9 6 3 0 10 6 6 0
Create lines using ggplot2 based on categorical column
Loading ggplot2 package and creating line chart based on values in factor column of df −
x<-rpois(10,5) y<-rpois(10,2) factor<-sample(0:1,10,replace=TRUE) df<-data.frame(x,y,factor) library(ggplot2) ggplot(df,aes(x,y,color=factor(factor)))+geom_line()
Output
- Related Questions & Answers
- How to create multiple regression lines using ggplot2 in R?\n
- How to create dotted vertical lines in a plot using ggplot2 in R?
- How to create a column with ratio of two columns based on a condition in R?
- How to subset an R data frame based on numerical and categorical column?
- How to create a categorical variable using a data frame column in R?
- How to create a scatterplot in base R with points depending on categorical column?
- How to color scatterplot points based on a threshold using ggplot2 in R?
- Create multiple regression lines in a single plot using ggplot2 in R.
- How to create two vertical lines on a plot with shaded area in-between using R?
- How to create an ID column in R based on categories?
- How to create a scatterplot with two legends using ggplot2 in R?
- How to create boxplots based on two factor data in R?
- How to find the number of unique values of multiple categorical columns based on one categorical column in R?
- How to divide row values of a numerical column based on categorical column values in an R data frame?
- How to create a subset based on levels of a character column in R?
Advertisements