如何在ggplot的geom_smooth()上使用manipulate()函数

3

有人知道如何在 ggplot 上使用 manipulate(),以便轻松选择平滑(span)级别吗?我已经尝试了以下内容,但没有成功:

# fake data
    xvals <- 1:10
    yvals <- xvals^2*exp(rnorm(2,5,0.6))
    data <- data.frame(xvals,yvals)

# plot with manipulate
    manipulate(
    ggplot(data,aes(xvals,yvals)) +
      geom_smooth(span=slider(0.5,5)) +
      geom_point()
    )

我希望能够轻松地在“平滑级别”之间切换。


受到这个例子的启发 - Dan
1个回答

5

将您的数据更改为具有更多数据点。

xvals <- 1:100
yvals <- rnorm(100)
data <- data.frame(xvals,yvals)

geom_smooth()中使用=的值必须有一个名称(例如,span.val),然后在ggplot()函数之外定义span.val=slider(0.1,1),作为manipulate()的第二个参数。

library(manipulate)
library(ggplot2)
manipulate({
  #define plotting function 
  ggplot(data,aes(xvals,yvals)) +
    geom_smooth(method="loess",span=span.val) +
    geom_point()},
  #define variable that will be changed in plot
    span.val=slider(0.1,1)
)

在ggplot()调用之外定义滑块值的原理是什么?我的意思是,manipulate()帮助页面建议在绘图调用内使用它。例如: plot(cars, xlim=c(x.min,x.max)), x.min=slider(0,15), x.max=slider(15,30)) - Dan
1
在您评论中的示例中,您可以看到函数plot()在逗号之前结束,然后x.min=slider(0,15)作为第二个参数传递给函数manipulate(),而不是plot()的参数。 - Didzis Elferts
我明白了,Didzis。这是 manipulate() 的参数而不是 plot() 的参数。谢谢 :) - Dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接