繁体   English   中英

计算R中成组的条形图中的条形数量并进行绘图

[英]Counting the number of bars in a grouped bar chart in R and plotly

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

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)

使用R Shiny的类似要求

您实际上要在这里做的是从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()元素),那么第一个元素应该是数据,并且上面的代码应该可以工作。

暂无
暂无

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

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