這是我的資料:
years bank hospital school police housing
2016 125 436 248 7.612 2.535
2017 167 497 281 8.215 3.145
2018 6064 2792 7564 38015 329
2019 2.972 3.070 14.771 40.180 371
2020 193 2.417 10.472 47.894 366
dput(fund)
structure(list(sector = c(2016, 2017, 2018, 2019, 2020), bank = c(125.2243,
167.4207, 6064.2903, 2971.6812, 192.7661), hospital = c(435.6579,
496.557, 2791.8501, 3070.4745, 2416.9531), school = c(248.476,
281.4527, 7564.4581, 14770.9388, 10471.76), police = c(7612.456,
8215.4141, 38014.6638, 40179.971, 47894.2436), housing = c(2534.8019,
3145.1998, 328.9033, 370.7749, 365.9282)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -5L))
這是我制作的代碼(我被困在服務器部分):
library(shiny)
ui <- fluidPage(titlePanel("Fund"),
selectInput(
inputId = "varbar1",
"choose....",
choices = c('bank',
'hospital',
'school',
'police',
'housing'
),selectize=FALSE),
plotOutput("bar1"))
server <- function(input, output) {
}
shinyApp(ui = ui, server = server)
我希望我的輸出是這樣的:

有人可以告訴我這如何作業,尤其是服務器部分的編碼
uj5u.com熱心網友回復:
該server部分可
server <- function(input, output) {
output$bar1 <- renderPlot({
barplot(fund[[input$varbar1]], names.arg = fund$sector, col = "red")
})
}
shinyApp(ui = ui, server = server)
-輸出

uj5u.com熱心網友回復:
我為這個問題找到了另一個解決方案,但這次我使用了 ggplot2 和 reshape2,這里是代碼:
library(shiny)
library(ggplot2)
library(reshape2)
ui <- fluidPage(titlePanel("Fund"),
selectInput(
inputId = "varbar1",
"choose....",
choices = c('bank',
'hospital',
'school',
'police',
'housing'
),selectize=FALSE),
plotOutput("bar1"))
server <- function(input, output) {
output$bar1<-renderPlot({
#reshape data
dfm <- melt(fund[,c("sector",input$varbar1)],id.vars = 1)
#barplot
ggplot(dfm,aes(x = factor(sector),y = value))
geom_bar(aes(fill = variable),stat = "identity",position = "dodge")
theme_minimal()
theme(panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.minor.x = element_blank())
})
}
shinyApp(ui = ui, server = server)
結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393451.html
