堆叠ggplot百分比条形图闪亮 [英] Stacked ggplot percent barchart in shiny

查看:653
本文介绍了堆叠ggplot百分比条形图闪亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


如何解决这个问题?



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



最好的结果是我设法得到闪亮

另外,我附上应用程序的可重现样本。



我的目标是在堆叠的百分比条形图绘制漂亮的标签 > ggplot 。

 库(闪亮)
库(shinydashboard)
库(plyr)
库(ggplot2)



#标题-------------------- ---------------------------------------

header< - dashboardHeader(title =DashBoard)


#边栏--------------------------- -----------------------------------

sm < - sidebarMenu(

menuItem(
text =堆叠条形图,
tabName =图表,
图标=图标(eye)




侧边栏< - dashboardSidebar(sm)

#正文----------------- ---------------------------------

body< - dashboardBody(

#布局------------------------------ --------------

tabItems(


tabItem(
tabName =chart,
fluidPage(

fluidRow(

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


plotOutput(M1),
dataTableOutput(outputId =M3)








#设置Shiny app UI组件-------------------------- -----------------

ui< - dashboardPage(header,sidebar,body)

#设置Shiny app back -end组件-------------------------------------

服务器< ; - 函数(输入,输出){






#------------ -------------------------------------------------- ---------------
#可重复数据生成
Mdata < - reactive({

set.seed(19 (c(Car,Bus,Bike),n,replace = TRUE,prob = NULL)
$ bn = 8

类别< b品牌< - 样品(品牌,n,替换= TRUE,概率=空)
品牌<-paste0(品牌,样品(1:14,n,替换= TRUE,概率= NULL))
USD < - abs(rnorm(n))* 100

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

#计算百分比
df = ddply(df,。(Brand),transform,percent = USD / sum(USD)* 100)


#格式化标签并计算它们的位置$ (美元) - 0.5 *美元))

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

})



输出$ M1< - renderPlot({

ggplot(Mdata(),aes(x = reorder(品牌,USD,$ b $函数(x)+ sum(x)),y =百分比,fill =类别))+
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()

})



输出$ M3< - renderDataTable({
Mdata()
})


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


}

#渲染Shiny app --------- -----------------------------------------------

shinyApp(ui,server)


解决方案

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



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



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

如何集中堆叠的百分比条形图标签


My aim is to create stacked bar chart with percent labels in ggplot. After some research and reading some material I've managed how to plot the chart I want. There a lot of 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)

However, I have 2 problems:

1) I can't find a proper place to put labels. You can see that labes are not centered and are in wrong sections. (plot generated not using shiny) How to solve this issue?

The second problem is when I try to use my plot code in shiny. I create labels using this function: df$label = paste0(sprintf("%.0f", df$percent), "%"), but when it is in reactive I get an error. In real case I have more difficult data generaration and subseting example, so my data must be reactive.

The best result I managed to get in shiny.

Also, I enclose reproducable esample of the app.

My aim is to plot nice labels for stacked percent bar chart in 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)

解决方案

The error from your paste0 command comes because it is the last line in the reactive, and thus becomes the return value. Just add a statement return(df) or something equivalent and that will fix that problem.

As for the label positioning, the code is working as designed, you will have to calculate the desired positions for the geom_text and use those coordinates explicitly.That will require you summing up the coordinates for each individual brand segment so you know its left and right positions and can calculate the center.

Other answers can be found in here:

How to center stacked percent barchart labels

这篇关于堆叠ggplot百分比条形图闪亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆