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

时间:2016-01-20 11:01:44

标签: r ggplot2 shiny bar-chart labels

我的目标是在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)我找不到放置标签的合适位置。您可以看到实验室没有居中并且处于错误的部分。 (不使用闪亮生成的情节) enter image description here 如何解决这个问题?

第二个问题是当我尝试在shiny中使用我的绘图代码时。 我使用这个函数创建标签:     df$label = paste0(sprintf("%.0f", df$percent), "%"),但当它在reactive时,我收到错误。在实际情况中,我有更难的数据生成和子组件示例,因此我的数据必须是reactive

我设法获得shiny的最佳结果。 enter image description here

另外,我附上了应用程序的可重复实例。

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

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)

1 个答案:

答案 0 :(得分:3)

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

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

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

How to center stacked percent barchart labels