问题
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)
回答1:
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.
来源:https://stackoverflow.com/questions/47037576/counting-the-number-of-bars-in-a-grouped-bar-chart-in-r-and-plotly