【问题标题】:for Python's plotnine, how to get % of count by total count in each facet对于 Python 的 plotnine,如何通过每个方面的总计数获得计数百分比
【发布时间】:2020-07-20 03:32:10
【问题描述】:

我正在尝试获取一个密度图,以显示每个方面的总数的计数百分比。

例如,我有这个密度图:

由此代码产生:

ggplot(data, aes(x = 'ratio'))                 

+ geom_histogram(aes(y = '..density..'),
                  binwidth = 0.5,                   
                  na_rm = True,                        
                  alpha = 0.8)                         

 + geom_vline(xintercept = 1, colour = 'red', linetype = 'dashed', size = 0.5)  # add a red vertical line
 
 + facet_grid('industry ~ state')              

 + labs(x = 'ratio', y = 'density')

 + scale_x_continuous(breaks = [0,1,2], labels = ['0','1','2'])    

 + theme(strip_text_y = element_text(angle = 0,         # angle text in y-fact (industry names)
                                     ha = 'left'),      # left alignment
         strip_background_y = element_text(width = 2.5),# change width of the grey box (on y)
         strip_background_x = element_text(width = 1),
         figure_size=(5, 5))     

如您所见,列的高度总和不等于 1。

如何确保每列的高度与每个分面的计数百分比相对应。

例如使用 facet (NSW, Construction) 作为示例。现在这是一个计数图:

NSW/Construction 方面的总和是 3760。 第 1 列、第 2 列...第 5 列的计数分别为 350、950、1630,630 和 200 我希望列显示:

  • 第一列 = 350/3760 = 9%
  • 第 2 列 = 950/3760 = 25%%
  • 第 3 列 = 1630/3760 = 43%
  • 第 4 列 = 630/3760 = 17%
  • 第 5 列 = 200/3760 = 5%

我尝试使用aes(y='..count../sum(..count..)'),但这让我计算出整个人口,而不是每个方面内的人口

请帮忙。

【问题讨论】:

    标签: python visualization plotnine


    【解决方案1】:

    使用aes(y=stat(width*density))

    从 R 的 ggplot2 上的帖子中得到这个想法,这是 plotnine 的基础。 https://github.com/tidyverse/ggplot2/issues/2499

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 2019-01-26
      • 2017-09-16
      • 1970-01-01
      • 2019-06-08
      相关资源
      最近更新 更多