使用Shiny和ggplot2在单个图上绘制多条线

3

我正在尝试构建一个应用程序,允许用户在单个图表上绘制多条线。我的数据包含多个国家的旅游数据,以年为单位。

> head(tourism)
  years Bulgaria Czech Republic   Denmark   Poland   Sweden   Norway
1  1995 5437.963       10274.98  9651.070 5523.500 7860.659 7294.971
2  1996 5921.961       13640.53 10810.187 5594.191 7716.620 7236.490
3  1997 5476.931       14932.49 10918.596 7579.637 7658.900 7243.111
4  1998 5197.050       16218.00 10287.564 7229.771 8029.087 7868.735
5  1999 4382.405       16125.00  9965.684 5644.924 8600.785 7814.983
6  2000 5170.091       15597.09 10005.887 6891.283 8654.086 7468.899

现在我正在尝试将数据绘制成以“年份”列为x轴,其他列为y轴的图表。

ui = fluidPage(
  titlePanel("Tourism"),
  sidebarLayout(
    sidebarPanel(
      selectizeInput("cnt",
                  "Select Country:",
                  choices = c("Bulgaria", 
                              "Czech Republic",
                              "Denmark",
                              "Poland",
                              "Sweden",
                              "Norway"),
                  selected = "Bulgaria",
                  multiple = TRUE
    )
    ),
    mainPanel(
      plotOutput("plot")
    )
  ) 
)


server = function(input, output) {

  output$plot = renderPlot({
    ggplot(tourism) +
      geom_line(mapping = aes(x = years, y = tourism[,input$cnt], colour = input$cnt)) + 
      labs (x = "Years", y = "Nights spent per 1000", title = "Tourism") + 
      scale_colour_discrete(name = "Country")
  })

}

shinyApp(ui = ui, server)

问题是,如果我试图同时绘制多个国家,我会收到以下错误提示:“美学必须是长度为1或与数据相同(21):x、y、颜色”。

在搜索时,我发现我缺少观察或响应部分,但我就是想不出如何添加它。

任何帮助都将不胜感激。

1个回答

3

将数据集转换为长格式,然后对其进行子集剖析以进行绘图。请尝试以下内容(未提供示例数据,因此我相信这将起作用,但未经测试):

#when loading server.R
library(reshape2)

然后:

 output$plot = renderPlot({
    plot.data <- melt(tourism, id.vars = 'years')
    #not sure if input$cnt is a list or a vector
    #may need to manipulate that before passing
    plot.data <- plot.data[plot.data$variable %in% input$cnt, ]
    ggplot(plot.data) +
      geom_line(mapping = aes(x = years, y = value, colour = variable)) + 
      labs (x = "Years", y = "Nights spent per 1000", title = "Tourism") + 
      scale_colour_discrete(name = "Country")
  })

修改了,打错了一个小字。 - Zach
1
正在打一些类似的东西 :) - Eric Watt

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