wom*_*ble 9 statistics plot r function ggplot2
有没有办法使用ggplot在数据之上叠加数学函数?
## add ggplot2
library(ggplot2)
# function
eq = function(x){x*x}
# Data
x = (1:50)
y = eq(x)
# Make plot object
p = qplot(
x, y,
xlab = "X-axis",
ylab = "Y-axis",
)
# Plot Equation
c = curve(eq)
# Combine data and function
p + c #?
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我的数据是使用函数生成的,但我想了解如何使用curve()ggplot.
rcs*_*rcs 16
你可能想要stat_function:
library("ggplot2")
eq <- function(x) {x*x}
tmp <- data.frame(x=1:50, y=eq(1:50))
# Make plot object
p <- qplot(x, y, data=tmp, xlab="X-axis", ylab="Y-axis")
c <- stat_function(fun=eq)
print(p + c)
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用curve(),即计算的x和y坐标:
qplot(x, y, data=as.data.frame(curve(eq)), geom="line")
Run Code Online (Sandbox Code Playgroud)