MetaPhilosopher
MetaPhilosopher

Reputation: 131

Error: Aesthetics must be either length 1 or the same as the data (1): x

Sorry if my question has been answered somewhere already, but all the other posts about "Aesthetics must be either length 1 or the same as the data" did not help me.

I'm trying to run the following code, but it gives this error: Error: Aesthetics must be either length 1 or the same as the data (1): x

library(tidyverse)

demand <- function(q) (q - 10)^2
supply <- function(q) q^2 + 2*q + 8

x <- 0:5

chart <- ggplot() +
  stat_function(aes(x), color = "Demand", fun = demand) +
  stat_function(aes(x), color = "Supply", fun = supply)
chart

What's wrong here?

The output should look like this:

enter image description here

Upvotes: 2

Views: 1819

Answers (1)

Paul
Paul

Reputation: 2977

According to ?ggplot2::stat_function(), this geom does not require data = .... This because "stat_function() computes the following variables: x values along a grid [and] y value of the function evaluated at corresponding x". The problem is related to the way you use x inside aes(). Please, look at the code below:

EDIT: I have added the possibility to use the x object to set the x-axis.

library(ggplot2)

demand <- function(q) (q - 10)^2
supply <- function(q) q^2 + 2*q + 8

x <- 0:5

chart <- ggplot() +
  stat_function(aes(color = "Demand"), fun = demand) +
  stat_function(aes(color = "Supply"), fun = supply) +
  xlim(min(x), max(x)) +
  scale_color_manual(name = "Legend",
                     values = c("Demand" = "red", "Supply" = "#24C6CA"))
chart

The output:

enter image description here

Is it what you are looking for? Note the use of xlim() to set the range of the x-axis.

Upvotes: 3

Related Questions