闪亮的堆叠 ggplot 百分比条形图

Stacked ggplot percent barchart in shiny

我的目标是在 ggplot 中创建带有百分比标签的堆积条形图。 经过一些研究和阅读一些 material 我已经设法绘制我想要的图表。有很多 material.

How do I label a stacked bar chart in ggplot2 without creating a summary data frame?

Create stacked barplot where each stack is scaled to sum to 100%

R stacked percentage bar plot with percentage of binary factor and labels (with ggplot)

但是,我有两个问题:

1) 我找不到合适的地方放标签。您可以看到标签没有居中并且位于错误的部分。 (未使用 shiny 生成的图) 如何解决这个问题?

第二个问题是当我尝试在 shiny 中使用我的情节代码时。 我使用此功能创建标签: df$label = paste0(sprintf("%.0f", df$percent), "%"),但是当它在 reactive 时,我得到一个错误。在实际情况下,我有更困难的数据生成和子集示例,所以我的数据必须是 reactive

我在 shiny 中取得的最好成绩。

此外,我附上了该应用程序的可重现示例。

我的目标是在 ggplot 中为 stacked percent bar chart 绘制漂亮的 labels

library(shiny)
library(shinydashboard)
library(plyr)
library(ggplot2)



# Header -----------------------------------------------------------

header <- dashboardHeader(title= "DashBoard")


# Sidebar --------------------------------------------------------------

sm <- sidebarMenu(

  menuItem(
    text="stacked bar chart",
    tabName="chart",
    icon=icon("eye")
  )  

)

sidebar <- dashboardSidebar(sm)

# Body --------------------------------------------------

body <- dashboardBody(

  # Layout  --------------------------------------------  

  tabItems(


    tabItem(
      tabName="chart",
      fluidPage(

        fluidRow(

          title = "Inputs", status = "warning", width = 2, solidHeader = TRUE, collapsible = TRUE,


          plotOutput("M1"),
          dataTableOutput(outputId="M3")


        )
      )
    )
  )
)

# Setup Shiny app UI components -------------------------------------------

ui <- dashboardPage(header, sidebar, body)

# Setup Shiny app back-end components -------------------------------------

server <- function(input, output) {






  # ----------------------------------------------------------------------------- 
  #reproducable data generation
  Mdata <- reactive({

    set.seed(1992)
    n=8

    Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
    Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
    Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
    USD <- abs(rnorm(n))*100

    df <- data.frame(Category, Brand, USD)

    # Calculate the percentages
    df = ddply(df, .(Brand), transform, percent = USD/sum(USD) * 100)


    # Format the labels and calculate their positions
    df = ddply(df, .(Brand), transform, pos = (cumsum(USD) - 0.5 * USD))

    #create nice labes
    #df$label = paste0(sprintf("%.0f", df$percent), "%")  

})



output$M1 <- renderPlot({ 

  ggplot(Mdata(), aes(x=reorder(Brand,USD,
                           function(x)+sum(x)),  y=percent, fill=Category))+
    geom_bar(position = "fill", stat='identity',  width = .7)+
    geom_text(aes(label=percent, ymax=100, ymin=0), vjust=0, hjust=2, color = "white",  position=position_fill())+
    coord_flip()+
    scale_y_continuous(labels = percent_format())+
    ylab("")+
    xlab("")

})  



output$M3 <- renderDataTable({
  Mdata()
})  


  # -----------------------------------------------------------------------------


}

# Render Shiny app --------------------------------------------------------

shinyApp(ui, server)

您的 paste0 命令出现错误是因为它是 reactive 中的最后一行,因此成为 return 值。只需添加一个语句 return(df) 或类似的语句即可解决该问题。

至于标签定位,代码按设计工作,您将必须计算 geom_text 所需的位置并使用这些坐标 explicitly.That 将要求您汇总坐标每个单独的品牌细分,以便您了解其左右位置并计算中心。

其他答案可以在这里找到: