在 R 中的数据点之上绘制函数 [英] Plotting functions on top of datapoints in R

查看:21
本文介绍了在 R 中的数据点之上绘制函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 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 #?

在这种情况下,我的数据是使用函数生成的,但我想了解如何将 curve() 与 ggplot 一起使用.

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

推荐答案

你可能想要 stat_function:

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)

如果你真的想使用 curve(),即计算出的 x 和 y 坐标:

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")

这篇关于在 R 中的数据点之上绘制函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆