Plotting simulated data points from f(X)+e using R Below is a chart from An Introduction to Statistical Learning by Hastie and Tibshirani. The authors use the chart to explain overfitting.
In the chart, Y is the response variable and X is the predictor variable. The black line represents the true model $f$. The circles represent data points from that model, given by $f(X)+\epsilon$, where $\epsilon$ is the random error with mean 0 and is independent of $X$.
I want to know how to plot the circles and the black curve in R, along with the assumptions that I have to make to produce something roughly 'of the sort'. $f$ looks like a cubic function to me.

 A: First, define your function $f(x)$; let's say $f(x)=x^3$ :
f <- function(x) x^3
(This function is vectorized: given a vector, it will cube each element of the vector.)
Define your set of $X$'s; the following gives you (1,3,...,99),for example:
X <- seq(1,99,2)
Generate some noise (standard normal here):
error <- rnorm(length(X),0,1)
Then you can generate the plot:
plot(X,f(X)+error,xlab="X",ylab="Y")
points(X,f(X),type='l')
A: Here's a minimal implementation of this kind of thing using ggplot.
library(ggplot2)

signal <- function(x) {x*(x-.9)^2}
x_linspace <- seq(0, 1, by = .01)
x_data <- runif(101, 0, 1)
y_true <- signal(x_linspace)
y_data <- signal(x_data) + rnorm(length(x_data), 0, .025)

plot_data <- data.frame(
  x_linspace=x_linspace, x_data=x_data, y_true=y_true, y_data=y_data
)

mm <- lm(y_data ~ poly(x_data, 2), data=plot_data)
plot_data$y_preds <- predict(mm, newdata=plot_data)

p <- (ggplot(data=plot_data) 
        + geom_point(aes(x=x_data, y=y_data))  # Scatter plot of data.
        + geom_line(aes(x=x_linspace, y=y_true))  # The true signal.
        + geom_line(aes(x=x_data, y=y_preds), color="blue")  # The fit parabola.
)


