2009-12-05 81 views
9

使用ggplot在數據頂部覆蓋數學函數嗎?在R中的數據點頂部繪製函數

## 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。

回答

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) 

,如果你真的想用curve(),即計算出的X和Y座標:

qplot(x, y, data=as.data.frame(curve(eq)), geom="line") 
3

鑑於你的問題的標題是「繪圖函數在R中「,下面介紹如何使用curve將函數添加到基R繪圖。

如之前

eq = function(x){x*x}; x = (1:50); y = eq(x) 

然後使用plot從基地圖形與add=TRUE參數來繪製點,隨後curve,添加的曲線創建的數據。

plot(x, y, xlab = "X-axis", ylab = "Y-axis") 
curve(eq, add=TRUE)