1

Reproducible example for data generation:

n <- 9
x <- 1:n
y <- rnorm(n)
data <- data.frame(x, y)

I know how to plot data with a spline without ggplot2.

plot(x, y, main = paste("spline[fun](.) "))
lines(spline(x, y))

plot image available here :

enter image description here

However, I want to plot a spline with ggplot2. Here is a code example:

ggplot(aes(x = x, y = y)) + geom_point() + geom_line(spline(data))

The error I get is: Error: data must be a data frame, or other object coercible by fortify(), not an S3 object with class uneval Did you accidentally pass aes() to the data argument?

Same error gets thrown if I use

ggplot(aes(data, x = x, y = y)) + geom_point() + geom_line(spline(data))

or

ggplot(aes(x = x, y = y)) + geom_point() + geom_line(spline(x, y))

or

ggplot(aes(x = data$x, y = data$y)) + geom_point() + geom_line(spline(data$x,data$y))

The following one gives different error. It was explored in here, but I want to plot a spline and am not sure how to apply the solution to my situation.

library(dplyr)
data %>% ggplot(aes(x = x, y = y)) + geom_point() + geom_line(spline(x, y))

Error: mapping must be created by aes()

Naresh
  • 16,698
  • 6
  • 112
  • 113
tRash
  • 131
  • 1
  • 11

1 Answers1

1

Possible way to do that:

ggplot(data, aes(x = x, y = y)) + 
  geom_point() + 
  geom_line(data = data.frame(spline(x, y))) #+
  #ggthemes::theme_base()

54942745

The problem is: spline returns list, you just should have convert it into data.frame and that's it.

utubun
  • 4,400
  • 1
  • 14
  • 17