How to Fix R Error: discrete value supplied to continuous scale

The error: discrete value supplied to continuous scale occurs in R when you “try to plot a categorical variable on a continuous scale and yet the variable on that axis is not numeric”.

library(ggplot2)

df <- data.frame(x = 1:10, y = c("bmw", "audi", "mercedez", "ferrari", "jaguar"))

ggplot(df, aes(x, y)) + geom_point() + scale_y_continuous(limits = c(0, 10))

Output

Error: Discrete value supplied to continuous scale

Please run the above code in RStudio because this is a problem of the plot, and visualizing the plots in RStudio is easy.

To create a plot using a continuous scale in ggplot2, you must define a continuous variable as the aesthetic for the x or y-axis.

We used the ggplot2 library in the above code to plot the data.

If you have not installed the ggplot2, you can install it in RStudio and by command.

install.packages("ggplot2")

After installing, you need to import the library in your R Script.

library(ggplot2)

The code you provided is causing the same error, “discrete value supplied to continuous scale” because you’re trying to plot a categorical variable “y” on a continuous scale.

Even if you set the limits of the y-axis to a range of continuous values, it doesn’t change the fact that the variable “y” is categorical.

How to fix error: discrete value supplied to continuous scale in R

There are two solutions to fix the error: discrete value supplied to continuous scale in R.

  1. Solution 1: Use the numeric vector.
  2. Solution 2: Map the categorical variable to a discrete scale, such as a factor, using the “as.factor()” function.

Solution 1: Use the numeric vector

library(ggplot2)

df <- data.frame(x = 1:10, y = c(1:5))

ggplot(df, aes(x, y)) + geom_point() 
         + scale_y_continuous(limits = c(0, 10))

Output

Use the numeric vector

Solution 2: Use the as.factor() function

To fix the error, another approach is to use the as.factor() function and convert the variable “y” to a factor before plotting it.

The as.factor() is a built-in R function that converts an R object like a vector or a data frame column from numeric to factor.

ggplot(df, aes(x, as.factor(y))) 
     + geom_point() 
     + scale_y_continuous(limits = c(0, 10))

It will probably resolve the error you are facing!

That’s it.

Leave a Comment