我正在Shiny中创建一个简单的应用程序,以了解其工作原理。
我有一个棒棒糖图表,该图表会根据用户输入进行更改。
图表按国家z-a排序。
我希望能够通过用户选择的数据(输入ID = dta)对其进行排序,从顶部的最大到底部的最小。
例如,我可以在普通R中做到这一点
data %>%
arrange(Market_size) %>%
mutate(Country = factor(Country, levels = Country)) %>%
ggplot(aes(y = Market_size, x = Country)) +
geom_lollipop(aes(color = Region), point.size = 5) +
theme(panel.background = element_blank(), axis.text.x = element_text(size =
13), axis.text.y = element_text(size = 13),
legend.text=element_text(size=13), legend.title=element_blank()) +
coord_flip() +
xlab("") +
ylab("") +
guides(colour = guide_legend(override.aes = list(size = 4)))
但是我似乎无法将其翻译为Shiny。
我对“ Shiny”这一部分的代码是:
# LIBRARIES AND DATA LOAD
library(shiny)
library(ggplot2)
library(readxl)
library(dplyr)
library(ggalt)
library(shinythemes)
library(DT)
library(plotly)
data <- read_excel("data.xlsx")
# USER INTERFACE
ui <- fluidPage(theme = shinytheme("flatly"),
navbarPage(title = "Database",
# HOME TAB
tabPanel("Home",
verticalLayout(
p(strong("Welcome to the database, select above the tabs to navigate."))
)
),
# SINGLE VARIABLE TAB
tabPanel("Single variable",
sidebarLayout(
sidebarPanel(
selectInput(inputId = "cntry",
label = "Choose countries:",
choices= data$Country,
multiple = TRUE),
selectInput(inputId = "rgns",
label = "Choose regions:",
choices= data$Region,
multiple = TRUE),
selectInput(inputId = "dta",
label = "Choose data:",
choices= names(data[3:6]),
multiple = FALSE)
),
mainPanel(
plotOutput(outputId = "plot")
)
)
)
)
)
# SERVER
server <- function(input, output) {
# DATA FOR SINGLE VARIABLE TAB AND SINGLE VARIABLE DATA TABLE
data_subset <- reactive({
filter(data, Country %in% input$cntry | Region %in% input$rgns) %>%
select(Country, Region, input$dta)
})
# PLOT FOR SINGLE VARIABLE TAB
output$plot <- renderPlot({
ggplot(data = data_subset(), aes_string(y = input$dta, x = "Country")) +
geom_lollipop(aes(color = Region), point.size = 5) +
theme(panel.background = element_blank(), axis.text.x = element_text(size =
13), axis.text.y = element_text(size = 13),
legend.text=element_text(size=13), legend.title=element_blank()) +
coord_flip() +
xlab("") +
ylab("") +
guides(colour = guide_legend(override.aes = list(size = 4)))
})
}
# RUN THE APP
shinyApp (ui = ui, server = server)
答案 0 :(得分:0)
尝试:
data_subset <- reactive({
filter(data, Country %in% input$cntry | Region %in% input$rgns) %>%
select(Country, Region, input$dta) %>%
mutate(y_var = .[[input$dta]]
})
然后在ggplot调用中,将第一行更改为:
ggplot(data = data_subset(), aes(y = y_var, x = Country))