简体   繁体   English

R Shiny 仪表板的堆栈条形图

[英]Stack Bar Plot For R Shiny Dashboard

How can I make a stack barchart for my Shiny Dashboard?如何为 Shiny Dashboard 制作堆栈条形图? For example I want one bar for 2016 with number of applications, number of accepted applications and the number enrolled, but all of these values together in one column - stacked.例如,我想要一个 2016 年的条形图,其中包含申请数量、接受的申请数量和注册数量,但所有这些值都放在一列中 - 堆叠。

this is my dataset这是我的数据集

You can use ggplot2 package to create stacked barplot with geom_bar(stat = "identity") .您可以使用ggplot2包创建带有geom_bar(stat = "identity")堆叠条形图。 However to convert wide data.frame format into narrow one required by ggplot2 it is neccessary to use melt function of reshape2 package.然而转换data.frame格式转换成由所需要的一个ggplot2这里有必要使用melt的功能reshape2包。

Please see the code below for barchart in Shiny Dashboard environement:请参阅下面的代码以获取 Shiny Dashboard 环境中的条形图:

# load the required packages
library(shiny)
require(shinydashboard)
library(ggplot2)
library(dplyr)

df <- read.table(text = "
Enrolment Applications Accepted Students Enrolled 
                 3 2017 30 25 5 20 
                 2 2016 24 21 3 20 
                 1 2015 22 20 2 17") 


#Dashboard header carrying the title of the dashboard
header <- dashboardHeader(title = "Basic Dashboard")  

#Sidebar content of the dashboard
sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard"))
    )
)


frow2 <- fluidRow(

  box(
    title = "Enrollement"
    ,status = "primary"
    ,solidHeader = TRUE 
    ,collapsible = TRUE 
    ,plotOutput("enrollement", height = "300px")
  )

)



# combine the two fluid rows to make the body
body <- dashboardBody(frow2)

#completing the ui part with dashboardPage
ui <- dashboardPage(title = 'This is my Page title', header, sidebar, body, skin='red')

# create the server functions for the dashboard  
server <- function(input, output) { 
  #creating the plotOutput content

  output$enrollement <- renderPlot({
    df$Enrolment <- factor(df$Enrolment)
    df$Not_Accepted <- df$Applications - df$Accepted
    df$Not_Enrolled <- df$Accepted - df$Enrolled
    df2 <- melt(df[, c("Enrolment", "Enrolled", "Not_Enrolled", "Not_Accepted")])

    ggplot(df2, aes(Enrolment, y = value, fill = variable)) +
      geom_bar(stat = "identity")
  })
}


shinyApp(ui, server)

Output:输出:

闪亮的仪表板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM