【问题标题】:R Shiny: not sure why ggplot is failingR Shiny:不知道为什么 ggplot 失败了
【发布时间】:2013-03-25 06:49:43
【问题描述】:

这里是闪亮的新手。

我正在尝试编写一个闪亮的 R 脚本,我想做的一件事是生成一个给定日期和不同地区给定广告客户的广告观看次数的直方图。

我的表有以下列(带有示例数据):

Date    Impressions Advertiser  Factor 1         DMA

2/19       22789     McDonalds   Cheap           Los Angeles
2/17       15002    Regal Cinem  Luxury          New York
2/20       12345     McDonalds   Cheap           D.C.

我在 UI 选项卡上想要的输出与 ggplot 类似

ggplot(df2, aes(x=DMA, y=Impressions, fill=DMA)) +geom_histogram()

应该是这样的

但是,我收到一个错误

Error: object 'DMA' not found

当我基本上将相同的公式粘贴到 R Shiny 中时。我的代码如下

服务器.R

library(shiny)
library(ggplot2)

df<- na.omit(read.csv("data.csv", fill= TRUE, nrows= 3000000))

shinyServer(function(input, output){

df2<- reactive({df[df$Date==input$date & df$Advertiser==input$name, ]})

#FIXME why is this plot not printing
output$plot1<- renderPlot({
  print(ggplot(df2, aes(x=DMA, y=Impressions, fill=DMA)) +geom_histogram())

})
#end of server brackets
})

ui.R

library(shiny)
df<- na.omit(read.csv("data.csv", fill= TRUE, nrows= 3000000))
daterange<- unique(df$Date)
names <- unique(df$Advertiser)

shinyUI(pageWithSidebar(

  #Title of Application
  headerPanel("Advertisement"), 

  sidebarPanel( 

    selectInput("date", "Date:", 
                choices= daterange),

    selectInput("name", "Partner", 
                choices= names)

  ),

  mainPanel(
    tabsetPanel(
      tabPanel("Plot1", plotOutput("plot1"))

      )
    )

  #end of UI brackets
  ))

其他一切都有效,包括标签。但是这个情节没有出现。

更新:谢谢,GGplot 现在通过将 print() 语句包裹在它周围来工作。但是,在无法找到变量的情况下出现了一个新问题。

【问题讨论】:

  • 你是说剧情正常,但在Shiny中不行?试着把你的情节放在print() 例如p &lt;- ggplot(...) + geom_histogram(...); print(p).
  • 谢谢。 ggplot 现在可以工作,但由于“找不到对象 DMA”而无法绘图
  • DMA 绝对是df2 中的一列吗?
  • 是的,df2 占据了 df 的所有列
  • 不要这么随便地忽略错误信息。如果 R 说它找不到 DMA,那么它真的 找不到 DMA。环境/评估可能会发生一些奇怪的事情,但在你走这条路之前,请绝对确保变量确实在数据框中。使用一些调试工具并在 ggplot 调用之前检查 df2

标签: r ggplot2 shiny


【解决方案1】:

df2 不是数据,而是一个反应函数。在ggplot 中使用df2(),并且不要忘记如上所述打印。

如果发生这种情况,不要假设“DMA 存在”,而是在关键点插入print(str(df2))

【讨论】:

  • 谢谢,解决了。对我来说,df 现在表示反应函数仍然不直观,需要一段时间才能习惯
【解决方案2】:

尝试用 print() 包装 ggplot 对象

【讨论】:

  • print() 是我在拼图中缺少的部分!
猜你喜欢
  • 1970-01-01
  • 2017-04-24
  • 2014-04-08
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多