2 Ways to Fix error: discrete value supplied to continuous scale

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

While continuous scale, you might face an error, and in today’s post, we will discuss that error and how to fix it.

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.

Let’s see the R code that generates the error.

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 plot and visualizing the plots in RStudio is easy.

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 easy ways to fix the error.

  1. Use the numeric vector.
  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, 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!

Conclusion

The error: discrete value supplied to continuous scale is raised when you plot a categorical variable on a continuous scale. The easy fix is using the numeric vector or converting the vector into a factor using the as.factor() function.

Leave a Comment