简体   繁体   中英

shiny ggplot with interactive y does not plot correctly

I am trying to create an interface where the user selects the y variables from a drop down menu and then can observe the bar chart with the observations selected. However, the output is not right as the app is not able to read my Y variables. Whenever I changed the Y variable from the drop down menu, the chart doesn't change at all.

Attached are screenshots of my csv data sheet, as well as the incorrect output chart I got from running the codes below:

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")

})

})

In the "as.list(c("Y2004","Y2005"....)" function I did not use "colnames(brand_sales)" because if I do, the column name "Brand" will also be shown in the drop down menu and I don't want that. I only want users to select a year between Y2004 and Y2015.

I have also tried "aes_string()" when referencing the columns in ggplot. But the output page generates the error "object 'Brands' not found".

Thanks to aosmith 's answer, I was able to fix the problem and got the chart to display correctly. It turns out that the correct codes to ggplot should be:

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

The key is to surround the X and Fill variables with quotes as this is the right way to name columns in aes_string.

Thanks again aosmith and MrFlink for your inputs!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM