我正在尝试创建一个交互式图表来在不同变量之间切换。其中一个变量是数字变量(年龄),但其他变量都是分类变量(性别、部门、职位)。我使用了在网上找到的代码和显示年龄分布的图表看起来不错,但我不知道如何让它显示分类变量。 我知道我的代码中遗漏了一些东西,但我无法弄清楚我需要什么。
这是我正在使用的数据集的链接:https://www.kaggle.com/datasets/adityaab1407/employee-productivity-and-satisfaction-hr-data?select=hr_dashboard_data.csv
这是我当前的代码:
library(shiny)
library(shinydashboard)
library(magrittr)
library(ggplot2)
ui <- dashboardPage(
skin = "purple",
dashboardHeader(title = "My dashboard"),
dashboardSidebar(
sidebarMenu()
),
dashboardBody(
fluidRow(
box(title = "Primary:", status = "primary", solidHeader = T, plotOutput("CPlot"), width = 7),
box(selectInput("myfile3", "Metric:", c("Age", "Gender", "Department", "Position")), width = 3)
),
)
)
server <- function(input, output){
# plot
Plot <- reactive({
ggplot(myfile3, aes(x = .data[[input$myfile3]])) +
geom_histogram(fill="#D55E00", color="#e9ecef", alpha=0.9) +
labs(
title = paste0("Distribution of ", paste0(input$myfile3), " employees in workplace"),
x = req(input$myfile3),
y = "Count") +
theme_minimal()
}) %>% bindEvent(input$myfile3)
output$CPlot <-output$DPlot <-output$EPlot <-output$FPlot <- renderPlot({Plot()})
}
shinyApp(ui = ui, server = server)
只需将
geom_bar()
(条形图)用于分类变量(即除 'Age'
之外的所有变量):
server <- function(input, output){
# plot
Plot <- reactive({
if (input$myfile3 == 'Age') {
ggplot(myfile3, aes(x = .data[[input$myfile3]])) +
geom_histogram(fill="#D55E00", color="#e9ecef", alpha=0.9) +
labs(
title = paste0("Distribution of ", paste0(input$myfile3), " employees in workplace"),
x = req(input$myfile3),
y = "Count") +
theme_minimal()
} else {
ggplot(myfile3, aes(x = .data[[input$myfile3]])) +
geom_bar(fill="#D55E00", color="#e9ecef", alpha=0.9) +
labs(
title = paste0("Distribution of ", paste0(input$myfile3), " employees in workplace"),
x = req(input$myfile3),
y = "Count") +
theme_minimal()
}
}) %>% bindEvent(input$myfile3)
output$CPlot <-output$DPlot <-output$EPlot <-output$FPlot <- renderPlot({Plot()})
}
您当然可以检查变量的类型(
class
)并相应地决定图表的类型,删除变量名称的硬编码'Age'
,这是当您从中选择'Department'
时得到的结果下拉菜单: