【问题标题】:R: How to plot statistic functions using rChartsR:如何使用 rCharts 绘制统计函数
【发布时间】:2015-01-05 11:26:16
【问题描述】:

我想使用rCharts 包绘制统计分布(如正态分布)。 我可以像这样使用curve 或 ggplot2 来绘制它。

曲线

curve(dnorm, xlim=c(-10,10))

ggplot2

ggplot(data.frame(x=c(-10,10)), aes(x)) + stat_function(fun=dnorm, args=list(0, 1))

我想使用rCharts 绘制统计函数,但我做不到。 如何绘制它?

【问题讨论】:

    标签: r plot rcharts


    【解决方案1】:

    您不能使用rChart 明确地做到这一点,但对于任何统计分布以及通常对于您想要的任何功能,您都可以很容易地做到这一点。您可以对d/r/p/q-distribution 形式的每个统计分布使用完全相同的技术,例如?rnorm?rbinom 等。但这甚至可以推广到您想要的任何 函数。我还包括一个通用函数的示例。

    对于使用dnormrnorm 的正态分布:

    x <- rnorm(1000) #you need rnorm here to create 1000 standard normally distributed observations. 
    y <- eval(dnorm(x)) #evaluate the function using dnorm now to get probabilities.
    #the use of eval() will be clear in the next example. Here you can even omit it if it confuses you.
    df <- data.frame(x,y) #make df
    
    #plot
    rPlot(y ~ x, data=df, type='line' )
    

    同样,对于二项分布,您可以使用dbinomrbinom 进行完全相同的操作。其他任何发行版都一样。

    您还可以根据@Gregor 的评论使用x = seq(-6, 6, length = 1000) 之类的东西而不是rnorm 函数来创建自定义x 变量,然后使用dnorm 生成相应的概率。这种方式的好处是可以直接设置x轴的范围。例如:

    a <- seq(-6,6,length=1000) #use -10,10 to reproduce your example
    b <- dnorm(a)
    df <- data.frame(a,b)
    rPlot(b~a,data=df,type='line')
    

    作为如何绘制任何函数的演示和概括

    我们以函数log(1+x) 为例。在这里,您将看到绘制任何函数是多么容易:

    x <- runif(1000,1,10) #1000 points are enough
    y <- eval(log(1+x)) #easily evaluate the function for your x vector
    #the previous was a very special case where you had 2 functions rnorm and dnorm
    #instead of an x vector and an f(x) function like here
    #this is very easy to generalize
    df <- data.frame(x,y) #make df
    
    #plot
    rPlot(y ~ x, data=df, type='line' )
    

    你可以用同样的方式使用任何你想要的功能!

    【讨论】:

    • 为什么要对 x 值进行采样,而不是仅仅做一个适当的序列,例如x = seq(-6, 6, length = 1000) 正常吗?
    • @Gregor 因为他的问题示例中的 OP 使用标准正态分布,所以我想使用相同的方法,最简单的方法是 rnorm 函数,他似乎也是熟悉,因为他知道dnorm。您的示例实际上是相同的,但说法不同。如果 OP 想要它,它肯定会发生。它改变了限制,所以我添加了一个注释和图表。
    • @Gregor 再三考虑,使用您的方式并定义整个 x 轴可能会更好。我想rnorm 是我首先想到的,可能是因为我经常使用它。再次感谢。
    • 我同意这样更好。定义 x 轴本质上是 OP 通过使用 curve() 并指定 xlim... 曲线默认使用 101 点所做的事情。
    • 另外,如果您对 ggplot2 感到满意,您可以使用 ggplot_build 作为 rCharts 的数据源
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    相关资源
    最近更新 更多