【问题标题】:Stacked ggplot percent barchart in shiny闪亮的堆叠ggplot百分比条形图
【发布时间】:2016-04-26 04:35:40
【问题描述】:

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

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 中使用我的绘图代码时。 我使用这个函数创建标签: 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(df) 或类似的内容,即可解决该问题。
  • 感谢@MikeWise 的帮助。它解决了第二个问题!只剩下一个问题,关于将标签放在正确的位置。
  • 我没有办法解决您的第一个问题。我认为代码正在按预期的方式工作。其他任何事情都会复杂得多,即您必须手动定位文本。我实际上认为hjust=1 看起来不错
  • 问题是,在实际情况下,例如,我有 10 年的数据。所以我添加selectInput 来更改年份。所以每次图表都会根据菜单中的选择重新绘制。
  • 我没有关注你。我看不出是什么问题导致标签的定位有问题?

标签: r ggplot2 shiny bar-chart labels


【解决方案1】:

来自paste0 命令的错误是因为它是reactive 的最后一行,因此成为返回值。只需添加声明 return(df) 或类似的内容,即可解决该问题。

至于标签定位,代码按设计工作,您必须计算 geom_text 的所需位置并明确使用这些坐标。这需要您汇总每个单独品牌细分的坐标,以便您知道它的左右位置,可以计算出中心。

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

How to center stacked percent barchart labels

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2012-09-05
    • 2014-10-31
    相关资源
    最近更新 更多