How to deal with Error: stat_count() can only have an x or y aesthetic in R?

R ProgrammingServer Side ProgrammingProgramming

To deal with Error: stat_count() can only have an x or y aesthetic, we need to pass the stat="identity" argument inside geom_bar function. Since we do not pass the count for bars and a bar graph can only contain only count variable, hence stat="identity" is needed so that geom_bar considers only one variable in aes for counting. Check out the below example to understand the difference.

Example

Consider the below data frame −

 Live Demo

factor<-sample(0:2,20,replace=TRUE)
col<-sample(6:8,20,replace=TRUE)
count<-rpois(20,8)
df<-data.frame(factor,col,count)
df

Output

   factor   col  count
1    2       7    7
2    0       8    8
3    0       6    9
4    0       7    8
5    1       7    10
6    0       6    12
7    2       6    10
8    1       6    8
9    0       6    9
10   0       7    8
11   0       8    3
12   2       8    11
13   1       7    14
14   0       7    10
15   1       8    13
16   0       8    5
17   2       8    10
18   2       7    8
19   1       6    9
20   2       8    9

Loading ggplot2 package and creating bar chart for categories in factor column −

library(ggplot2)
ggplot(df,aes(factor,count,fill=col))+geom_bar()

Error − stat_count() can only have an x or y aesthetic.

Run `rlang::last_error()` to see where the error occurred.

Creating the bar chart with stat="identity" −

Example

ggplot(df,aes(factor,count,fill=col))+geom_bar(stat="identity")

Output

raja
Published on 06-Mar-2021 16:17:18
Advertisements