0

When I run this script below, It gives me two grouped bar charts. I simply want a vector with the count of number of bars in each group. Attaching the snapshot for reference, clearly, the vector will have two count values. Please help.

library(shiny)
library(shinydashboard)
library(ggplot2)
library(plotly)
ui <- dashboardPage(
dashboardHeader(title = "Sankey Chart"),
dashboardSidebar(
width = 0
),
dashboardBody(
fluidRow(
column(10,
     uiOutput('box1'),
     tags$br()),
tags$br(),
column(10,


     box(title = "Case Analyses",status = "primary",solidHeader = 
T,width = 1050,height = 452,
         plotlyOutput("case_hist"))
))
)
)
server <- function(input, output) 
{ 
output$case_hist <- renderPlotly(
{

iris$iris_limits <- cut(iris$Sepal.Length, c(1,3,6,9))
iris$ID <- factor(1:nrow(iris))
gg <- ggplot(iris, aes(x=ID, y=Sepal.Length, fill=iris_limits)) + 
geom_bar(stat="identity", position="dodge") +
facet_wrap(~iris_limits, scales="free_x", labeller=label_both) +
theme_minimal() + xlab("") + ylab("Sepal Length") +
theme(axis.text.x=element_blank())
ggplotly(gg)
}
)
output$box1 <- renderUI({
tagList(
infoBox("Total Cases", "a" , icon = icon("fa fa-briefcase"))
)
})
}
shinyApp(ui, server)

Similar requirement using R shiny

Ashmin Kaul
  • 860
  • 2
  • 12
  • 37

1 Answers1

0

What you're effectively trying to do here is extract data from the plot element. In this case, we can do this by extracting the plot data and storing it in a temporary data frame, then making a table of the PANEL variable to see how many elements are in each panel.

gg<- ggplot(df, aes(alpha, bravo))  # however you made your plot
temp <- data.frame(ggplot_build(gg)$data[[1]]) 
table(temp$PANEL)

edit: the plot I was playing with to create this answer had the data applied as the third element, thus I originally had a 3 instead of 1 in line two of the code. Replace that number with whichever layer has your data. If you do a simple plot that only has one element (like yours with geom_bar() first above) then your first element should be the data and the code above should work.

cparmstrong
  • 799
  • 6
  • 23
  • Thanks for the help, I have edited this post, please help me with the similar requirement in R shiny. – Ashmin Kaul Nov 01 '17 at 05:48
  • If I click on any bar in the grouped bar chart say "red" or "green", I should get the total bars displayed in the infobox above belonging to that grouped bar chart – Ashmin Kaul Nov 01 '17 at 06:25
  • @AshminKaul it's standard procedure around here to not edit a post to ask for additional support, but instead create a new one. I'm not as familiar with shiny anyways so I can't help you there. – cparmstrong Nov 01 '17 at 12:34
  • @AshminKaul, instead of editing a question for which you already have an accepted answer, you should post a new question. – SBista Nov 01 '17 at 13:19