首页 文章

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

提问于
浏览
4

我的目标是在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 时,我收到错误 . 在实际情况下,我有更困难的数据生成和subseting示例,所以我的数据必须是 reactive .

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

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

我的目标是在 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)

1 回答

  • 3

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

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

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

    How to center stacked percent barchart labels

相关问题