How to display count on Y-axis for line chart using ggplot2 in R?

R ProgrammingServer Side ProgrammingProgramming

To display count on Y-axis for line chart using ggplot2 in R, we can follow the below steps −

  • First of all, create a data frame.

  • Then, create the line chart using geom_line function of ggplot2 package with fill argument counting the values using count function and binwidth set to 1.

Create the data frame

Let’s create a data frame as shown below −

 Live Demo

x<-sample(1:10,200,replace=TRUE)
df<-data.frame(x)
head(df,25)

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

Output

  x
1 6
2 5
3 4
4 3
5 2
6 6
7 7
8 4
9 5
10 5
11 1
12 2
13 10
14 7
15 7
16 8
17 3
18 8
19 3
20 1
21 8
22 9
23 5
24 6
25 5

Create the line chart with display of count on Y-axis

Loading ggplot2 package and using fill=..count.. inside aes of geom_line along with binwidth of 1 to create the line chart count on Y-axis −

x<-sample(1:10,200,replace=TRUE)
df<-data.frame(x)
library(ggplot2)
ggplot(df,aes(x))+geom_line(aes(fill=..count..),stat="bin",binwidth=1)
Warning message:
Ignoring unknown aesthetics: fill

Output

raja
Published on 11-Aug-2021 08:04:21
Advertisements