How to create line chart for categories with grey color palette using ggplot2 in R?


To create line chart for categories with grey color palette using ggplot2, we can follow the below steps −

  • First of all, create a data frame.
  • Then, create the line chart for categories with default color of lines.
  • Create the line chart for categories with color of lines in grey palette.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-rnorm(25)
y<-rnorm(25)
Factor<-factor(sample(1:3,25,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   0.16617082  0.6440847 2
2   0.64861850  0.0894490 3
3   2.23253199  0.9830666 3
4   0.15959321 -1.5818475 3
5   0.99115481  0.3007150 3
6  -0.11421911 -0.0597798 2
7  -2.18767456  0.4199796 1
8  -0.45615151 -0.9753236 3
9   0.31962740 -0.1656778 1
10 -0.26188647 -1.4247906 1
11 -0.07914911 -1.1719439 1
12  0.04386646 -0.6051025 1
13  0.30364566  0.3973123 3
14  1.91715394  0.4858528 3
15 -1.31486210 -2.2679916 1
16 -0.64839356 -1.9870203 1
17 -1.04466289 0.5891917  1
18  0.21874848 -0.2328089 1
19  1.27746893  0.6943986 3
20  0.49281808 -1.0389503 3
21  0.13930975  0.3550664 2
22  1.02323729  1.5719230 3
23  1.31209069 -1.6987137 1
24  0.99838299  1.2443123 2
25  0.64388089  1.1059815 2

Create line chart with lines in default colors

Loading ggplot2 package and creating line chart with default colors of violins −

x<-rnorm(25)
y<-rnorm(25)
Factor<-factor(sample(1:3,25,replace=TRUE))
df<-data.frame(x,y,Factor)
library(ggplot2)
ggplot(df,aes(x,y,colour=Factor))+geom_line()

Output

Create line chart with lines in grey color palette

Use scale_fill_grey to create the line chart with lines in grey color palette −

x<-rnorm(25)
y<-rnorm(25)
Factor<-factor(sample(1:3,25,replace=TRUE))
df<-data.frame(x,y,Factor)
library(ggplot2)
ggplot(df,aes(x,y,colour=Factor))+geom_line()+scale_color_grey()

Output

Updated on: 13-Aug-2021

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements