我制作了一个多项式函数图:y = x ^ 2 - 6 * x + 9
序列中有几个点+ y中的次要标准误。我使用这些点从原始数据点构造该函数的样条模型,然后我使用R的predict()函数计算样条模型的导数,然后将两条样条曲线添加到图中。
顺便说一句,预期的导数函数是这样的:dy / dx = 2 * x - 6
原来的功能我用蓝色和第一衍生功能我用红色。我希望在这些图中添加图例,但我发现这很难,因为我没有为图分配任何点,因为我在geom_smooth()函数中声明了数据帧。
我正在使用的代码是:
library(ggplot2)
# Plot the function: f(x) = x^2 - 6x + 9
# with a smooth spline:
# And then the deriviative of that function from predicted values of the
# smoothed spline: f ' (x) = 2*x - 6
# Get a large sequence of x-values:
x <- seq(from = -10, to = 10, by = 0.01)
# The y-values are a function of each x value.
y <- x^2 - 6*x + 9 + rnorm(length(x), 0, 0.5)
# Fit the curve to a model which is a smoothed spine.
model <- smooth.spline(x = x, y = y)
# Predict the 1st derivative of this smoothed spline.
f_x <- predict(model, x = seq(from = min(x), to = max(x), by = 1), deriv = 1)
# Plot the smoothed spline of the original function and the derivative with respect to x.
p <- ggplot() + theme_bw() + geom_smooth(data = data.frame(x,y), aes(x = x, y = y), method = "loess", col = "blue", se = TRUE) + geom_smooth(data = data.frame(f_x$x, f_x$y), aes(x = f_x$x, y = f_x$y), method = "loess", col = "red", se = TRUE)
# Set the bounds of the plot.
p <- p + scale_x_continuous(breaks = scales::pretty_breaks(n = 20), limits = c(-5, 10)) + scale_y_continuous(breaks = scales::pretty_breaks(n = 20), limits = c(-10, 10))
# Add some axis labels
p <- p + labs(x = "x-axis", y = "y-axis", title = "Original Function and predicted derivative function")
p <- p + scale_fill_manual(values = c("blue", "red"), labels = c("Original Function", "Derivative Function with respect to x"))
print(p)
我希望我可以使用scale_fill_manual()添加图例,但我的尝试不会在图中添加图例。基本上,我得到的情节通常看起来像这样,减去我在油漆中添加的杂乱传奇。我想要那个传奇,谢谢。
我这样做是因为我想向我的化学讲师表明,我可以从差示扫描量热法数据中精确测量热容量,我相信热容量只是热流与温度的第一个导数图。区别于温度。
所以我试图绘制一个图表,显示原始函数覆盖了相对于x的一阶导数函数,表明只有符合原始数据点的样条曲线的一阶导数图可靠地产生预期的线dy / dx = 2 * x - 6,它确实如此。
我只想添加那个传奇。
答案 0 :(得分:3)
使用数据创建数据框并在美学中使用颜色是最常见的方法。
df <- rbind(
data.frame(data='f(x)', x=x, y=y),
data.frame(data='f`(x)', x=f_x$x, y=f_x$y))
p <- ggplot(df, aes(x,y, color=data)) + geom_smooth(method = 'loess')
p <- p + scale_x_continuous(breaks = scales::pretty_breaks(n = 20), limits = c(-5, 10)) + scale_y_continuous(breaks = scales::pretty_breaks(n = 20), limits = c(-10, 10))
p <- p + labs(x = "x-axis", y = "y-axis", title = "Original Function and predicted derivative function")
p <- p + scale_color_manual(name = "Functions", values = c("blue", "red"), labels = c("Original Function", "Derivative Function with respect to x"))
print(p)