[英]Plotting multiple lines on a single graph using Shiny and ggplot2
我正在嘗試構建一個應用程序,讓用戶在一個圖表上繪制多行。 我的數據包含多個國家/地區的旅游數據。
> 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
現在我正在嘗試繪制數據,其中'years'列為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,顏色”。
在搜索時,我發現我錯過了觀察或反應部分,但我無法弄清楚如何添加它。
任何幫助,將不勝感激。
將您的數據集融合為長格式,然后將子集融合到繪圖中。 嘗試以下(沒有提供樣本數據,所以我很確定這將工作,但沒有測試):
#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")
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.