【问题标题】:shiny ggplot with interactive y does not plot correctly具有交互式 y 的闪亮 ggplot 无法正确绘制
【发布时间】:2016-04-20 04:16:09
【问题描述】:

我正在尝试创建一个界面,用户可以在其中从下拉菜单中选择 y 变量,然后可以观察带有所选观察值的条形图。 但是,输出不正确,因为应用程序无法读取我的 Y 变量。每当我从下拉菜单中更改 Y 变量时,图表根本不会改变。

附件是我的 csv 数据表的截图,以及我运行以下代码得到的错误输出图表:

enter image description here

enter image description here

shinyUI(fluidPage(
titlePanel("Volvo Sales Analysis"),

fluidRow(

  column(4,selectInput("Year",
              label = "Choose a year",
              choices = as.list(c("Y2004","Y2005","Y2006","Y2007","Y2008","Y2009","Y2010","Y2011","Y2012",
                          "Y2013", "Y2014", "Y2015")),selected = "Y2015")),

  column(12,plotOutput("brandplot"))

  )
))


shinyServer(
function(input, output) {

brand_sales<-read.csv("C:/Shiny R/Sales by brand.csv", header=TRUE,check.names=FALSE)

output$brandplot= renderPlot({

ggplot(brand_sales,aes(x=brand_sales$Brands,y=input$Year,fill=Brands))+xlab("Brands")+ylab("Sales Volume")+geom_bar(stat="identity")

})

})

在 "as.list(c("Y2004","Y2005"....)" 函数中我没有使用 "colnames(brand_sales)" 因为如果我这样做了,列名 "Brand" 也将是显示在下拉菜单中,我不希望这样。我只希望用户在 Y2004 和 Y2015 之间选择一年。

在引用 ggplot 中的列时,我也尝试过“aes_string()”。但是输出页面会生成错误“找不到对象'Brands'”。

【问题讨论】:

  • 当你想指定一个列时,你不应该使用aes()。尝试搜索aes_string() 也许this example 会有所帮助。
  • 我尝试了 aes_string() 但输出页面生成错误“找不到对象‘品牌’。
  • Brands 放在aes_string 的引号中(所有变量都应放在引号中)。
  • @aosmith:我也试过“aes_string(x="Brands", y=input$Year, fill=Brands)”。错误依然存在:(
  • fill = "Brands" 代替fill = Brands。查看aes_string 的帮助页面,那里有一个示例。

标签: r ggplot2 shiny interactive


【解决方案1】:

感谢aosmith的回答,我得以解决问题并让图表正确显示。事实证明,ggplot 的正确代码应该是:

"ggplot(brand_sales,aes_string(x="Brands",y=input$Year,fill="Brands"))+xlab("Brands")+ylab("销售量")+geom_bar(stat="身份")"

关键是用引号括住 X 和 Fill 变量,因为这是在 aes_string 中命名列的正确方法。

再次感谢 aosmithMrFlink 的投入!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2019-05-20
    • 2022-01-20
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2018-12-12
    相关资源
    最近更新 更多