- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 deal with Error: stat_count() can only have an x or y aesthetic in R?
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 −
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
- Related Articles
- How to deal with error “var(x) : Calling var(x) on a factor x is defunct.” in R?
- How to deal with “could not find function” error in R?
- How to deal with error invalid xlim value in base R plot?
- How to deal with error “$ operator is invalid for atomic vectors” in R?
- How to deal with error “undefined columns selected” while subsetting data in R?
- How to deal with the error “Error in int_abline---plot.new has not been called yet” in R?
- How to deal with error “Error in shapiro.test(…) : sample size must be between 3 and 5000” in R?
- How to deal with error “undefined columns selected when subsetting data frame” in R?
- How to deal with glm.fit error “NA/NaN/Inf” for logistic regression model in R?
- How to deal with hist.default, 'x' must be numeric in R?
- How to deal with error “Error in eval(predvars, data, env) : numeric 'envir' arg not of length one” in R?
- How to deal with error 'height' must be a vector or a matrix while creating barplot?
- How to deal with NA output of apply in R?
- How to deal with missing values to calculate correlation matrix in R?
- How to plot values with log scales on x and y axis or on a single axis in R?

Advertisements