R Shiny: Why doesn't ggplot work?

风格不统一 提交于 2019-12-11 06:57:55

问题


I'm trying to make a plot using ggplot2 for the following data: data

Name       date   weight   height 
Cat1 2016-03-01 34.20000 22.50000
Cat1 2016-04-01 35.02080 23.01750
Cat1 2016-05-01 35.86130 23.54690
Cat1 2016-06-01 36.72197 24.08848
Cat2 2016-03-01 33.55000 22.96000
Cat2 2016-04-01 33.61710 23.41920
Cat2 2016-05-01 33.68433 23.88758
Cat2 2016-06-01 33.75170 24.36534

The code I'm using:

library("shiny")
library("xlsx")
library("ggplot2")

animal <- read.xlsx("C:\\data\\animals.xlsx",1)

ui<- fluidPage(
 titlePanel("Animals"),
 sidebarLayout(
 sidebarPanel(
  helpText("Create graph of height or weight animals"),

  selectInput("anim", 
              label = "Choose an animal",
              choices = c("Cat1", "Cat2"),
              selected = "Cat1"),

  selectInput("opti", 
              label = "Option",
              choices = c("weight", "height"),
              selected = "weight")
  ),
  mainPanel(plotOutput("graph"))
))

server <- function(input, output){
   output$graph <- renderPlot({
   p2 <- ggplot(subset(animal, Name %in% input$anim)) + geom_line(aes(x=date, y = input$opti)) 
  print(p2)
})
}
 shinyApp(ui=ui, server= server)

I don't get an error, but the output of the plot is just a straight line (plot). I don't understand why, if I put the code in the command window with ggplot, it does work.


回答1:


Since your y aesthetic is a user-provided input rather than a hard-coded R identifier, you need to use aes_string instead of aes:

p2 = ggplot(subset(animal, Name %in% input$anim)) +
    geom_line(aes_string(x = 'date', y = input$opti))

Note that you now need quotes around the x aesthetic.

Side-note: you can print ggplots, but I always find that weird: what does printing a plot mean?1plot it instead:

plot(p2)

It does the same, it just looks more logical.


1 For the record, I know why ggplot2 provides a print function. It’s a neat trick. It just doesn’t make sense to call it explicitly.



来源:https://stackoverflow.com/questions/38848897/r-shiny-why-doesnt-ggplot-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!