【问题标题】:Plotting functions on top of datapoints in R在 R 中的数据点之上绘制函数
【发布时间】:2010-12-23 15:31:33
【问题描述】:

有没有一种方法可以使用 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 一起使用。

【问题讨论】:

    标签: r function statistics plot ggplot2


    【解决方案1】:

    你可能想要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")
    

    【讨论】:

      【解决方案2】:

      鉴于您的问题标题是“在 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)
      

      【讨论】:

        猜你喜欢
        • 2015-01-24
        • 1970-01-01
        • 1970-01-01
        • 2016-07-31
        • 1970-01-01
        • 1970-01-01
        • 2012-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多