[英]Plotting functions on top of datapoints in R
有沒有辦法使用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 #?
在這種情況下,我的數據是使用函數生成的,但我想了解如何將curve()
與ggplot一起使用。
你可能想要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)
如果你真的想使用curve()
,即計算的x和y坐標:
qplot(x, y, data=as.data.frame(curve(eq)), geom="line")
鑒於您的問題標題是“在R中繪制函數”,這里是如何使用curve
將函數添加到基礎R圖。
像以前一樣創建數據
eq = function(x){x*x}; x = (1:50); y = eq(x)
然后使用plot
從基地圖形繪制點,隨后curve
與add=TRUE
參數,添加的曲線。
plot(x, y, xlab = "X-axis", ylab = "Y-axis")
curve(eq, add=TRUE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.