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

查看:101
本文介绍了在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() with 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天全站免登陆