计算R中的分组条形图中的条形数和图形

时间:2017-10-31 14:16:42

标签: r ggplot2 plotly ggplotly

当我在下面运行这个脚本时,它给了我两个分组的条形图。我只想要一个带有每组中条数的矢量。附上快照以供参考,显然,矢量将具有两个计数值。请帮忙。

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

1 个答案:

答案 0 :(得分:0)

你在这里有效地尝试做的是从plot元素中提取数据。在这种情况下,我们可以通过提取绘图数据并将其存储在临时数据框中,然后创建PANEL变量表来查看每个面板中有多少元素。

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

编辑:我正在玩的用于创建此答案的图表将数据应用为第三个元素,因此我最初在代码的第二行中使用了3而不是1。用您的数据中的任何一层替换该数字。如果你做一个只有一个元素的简单图(就像你的geom_bar()一样),那么你的第一个元素应该是数据,上面的代码应该可以工作。