[英]Plotting functions on top of datapoints in R
Is there a way of overlaying a mathematical function on top of data using ggplot? 有没有办法使用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. 在这种情况下,我的数据是使用函数生成的,但我想了解如何将
curve()
与ggplot一起使用。
You probably want stat_function
: 你可能想要
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()
, ie, the computed x and y coordinates: 如果你真的想使用
curve()
,即计算的x和y坐标:
qplot(x, y, data=as.data.frame(curve(eq)), geom="line")
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. 鉴于您的问题标题是“在R中绘制函数”,这里是如何使用
curve
将函数添加到基础R图。
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
从基地图形绘制点,随后curve
与add=TRUE
参数,添加的曲线。
plot(x, y, xlab = "X-axis", ylab = "Y-axis")
curve(eq, add=TRUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.