一个R Shiny问题 - 在一个图中绘制多条线

4

目前,我的代码会让用户首先选择他们想要的数据集(提供两个选项)。然后根据他们的选择,数据集各自子集的其他绘图变量就会出现。这个功能运行良好,除了一点,我希望把这些图形叠加到同一个图中,而不是分开显示。

我有一个默认图plot_Total,而数据集中的其他选项都是查看它的特定子集。因此,只有一个散点图是有意义的。

 output$plot_Total <- reactivePlot(function() { 
  plot.new()
   plot.window(xlim=c(1850,2020), ylim = c(0,5000000))
   axis(1)
   axis(2)
   title(main="Numbers over the years")
   title(xlab="Year")
   title(ylab="Number of people")
   box()
   points(dat$Year, dat$Total, col="red")
   lines(dat$Year, dat$Total, col="red")
   })

 output$plot_subset1 <- reactivePlot(function() { lines(dat$Year, dat$subset1) })
 output$plot_subset2 <- reactivePlot(function() { lines(dat$Year, dat$subset2) })

为什么这段代码不起作用?每个(不需要的)图形仅创建空白区域,在下面显示“错误:尚未调用 plot.new”。如何指定将这些线添加到默认(plot_Total)绘图中?

3
你看过Shiny主页上的例子吗?它似乎可以通过在现有绘图中添加低级别绘图命令来实现你想要的功能:http://www.rstudio.com/shiny/ - Chase
1个回答

7

更新:通过调整闪亮首页上图形的代码,我意识到我必须这样做:

 output$plot_Total <- reactivePlot(function() { 
  plot.new()
   plot.window(xlim=c(1850,2020), ylim = c(0,5000000))
   axis(1)
   axis(2)
   title(main="Numbers over the years")
   title(xlab="Year")
   title(ylab="Number of people")
   box()
   points(dat$Year, dat$Total, col="red")
   lines(dat$Year, dat$Total, col="red")
  if (input$RC) {   lines(dat$Year, dat$dat)}
  })

这与我的原始代码有两个不同之处。首先,在同一反应绘图函数中添加条件作为一行。其次,我创建了一个新的data.frame,其中只包含RC子集。最初,input$dat$RC不能正常工作,但当RC是自己的数据框时,它将作为input$RC工作。
感谢Chase指导我朝正确的方向前进!

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