在 R 中的数据点之上绘制函数

发布于 2024-08-13 04:54:08 字数 477 浏览 2 评论 0原文

有没有办法使用 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 一起使用。

Is there a way of overlaying a mathematical function on top of data using 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 #?

In this case my data is generated using the function, but I want to understand how to use curve() with ggplot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

影子是时光的心 2024-08-20 04:54:08

您可能需要 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")

You probably want 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)

and if you really want to use curve(), i.e., the computed x and y coordinates:

qplot(x, y, data=as.data.frame(curve(eq)), geom="line")
世界如花海般美丽 2024-08-20 04:54:08

鉴于您的问题标题是“在 R 中绘制函数”,以下是如何使用 curve 将函数添加到基本 R 图中。

像以前一样创建数据

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

然后使用基础图形中的plot来绘制点,然后使用curveadd=TRUE参数来添加曲线。

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

Given that your question title is "plotting functions in R", here's how to use curve to add a function to a base R plot.

Create data as before

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

Then use plot from base graphics to plot the points followed by curve with the add=TRUE argument, to add the curve.

plot(x, y,  xlab = "X-axis", ylab = "Y-axis") 
curve(eq, add=TRUE)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文