R ggplot2 Error: Aesthetics Must be Either Length 1 or Same as Data (2 Examples)
In this post you’ll learn how to fix the error message “Aesthetics must be either length 1 or the same as the data” in R.
Preparing the Examples
data(iris) # Loading some data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading some data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2")
Example 1: Replicate the Error Message: Aesthetics must be either length 1 or the same as the data
ggplot(iris, aes(x = Species, # Wrong specification of fill argument y = Sepal.Width, fill = 1:5)) + geom_bar(stat = "identity") # Error: Aesthetics must be either length 1 or the same as the data (150): fill |
ggplot(iris, aes(x = Species, # Wrong specification of fill argument y = Sepal.Width, fill = 1:5)) + geom_bar(stat = "identity") # Error: Aesthetics must be either length 1 or the same as the data (150): fill
Example 2: Solve the Error Message: Aesthetics must be either length 1 or the same as the data
ggplot(iris, aes(x = Species, # Correct specification y = Sepal.Width, fill = Species)) + geom_bar(stat = "identity") |
ggplot(iris, aes(x = Species, # Correct specification y = Sepal.Width, fill = Species)) + geom_bar(stat = "identity")