I have a small dataset that can be well-described with an exponential function, and I can solve for this function's parameters if I first get appropriate starting values using a log-transform:
x <- c(seq(from = 10, to = 200, by = 10), seq(from = 230, to = 590, by = 30))
y <- c(32.403, 38.832, 46.023, 59.895, 75.385, 98.283, 134.474, 186.62, 243.293,
307.713, 383.845, 468.155, 567.619, 684.183, 810.969, 969.507, 1135.038,
1320.475, 1530.365, 1757.032, 2587.402, 3633.337, 4939.983, 6526.32, 8436.739,
10679.428, 13280.434, 16259.746, 19651.199, 23636.122, 27849.712, 32704.141, 38291.655)
simulationData <- data.frame(x = x, y = y)
model.0 <- lm(log(y) ~ x, data=simulationData)
start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2])
model <- nls(y ~ a * exp(b * x), data = simulationData, start = start)
qplot(x, y, data = augment(model)) + geom_line(aes(y = .fitted)) +
theme(text = element_text(size=20), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
This qplot
command, however, only plots fitted values for the relatively limited vector of x-values I have, and thus the curve is really just composed of line segments and doesn't look smooth.
I can generate a more fine grid of x-values, and use the parameters from the nls model to plot a smooth function:
dense_x <- seq(0.1, 600, by = 0.1)
df <- data.frame(dense_x)
ggplot(df,aes(dense_x))+
stat_function(fun=function(dense_x) 10.34436 * exp(0.00719 * dense_x)) +
theme(text = element_text(size=20), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
theme_bw()
But I can't figure out how to combine these two plots, since they have separate mappings (one is the original data, which I want to include as points in the plot, the other is the data for the curve fitting, which I only want to use to plot this function).
Does anyone know the appropriate way to generate such a plot. Maybe there is a way to flag just a subset of x values to be included in a geom_point()
call?
Thanks!
You should be able to move the assignment of data and the x/y values from ggplot to the geoms you want to plot. So rather than inheriting them globally each individual geom can be assigned different data and aesthetics. That way you can combine different plots--even with the same type geom layer:
ggplot() +
geom_scatter(df1, aes(x1, y1)) +
geom_scatter(df2, aes(x2, y2))
Alternatively, as you suggest in the comment, you can add a different layer to your existing plot where you had defined data and mapping in the ggplot() function and simply designate a new dataset and mapping for this new layer.