Plotting functions on top of datapoints in R

断了今生、忘了曾经 提交于 2019-12-29 04:22:24

问题


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.


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/1853703/plotting-functions-on-top-of-datapoints-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!