对于 Python 的 plotnine,如何获得每个方面总计数的百分比
for Python's plotnine, how to get % of count by total count in each facet
我正在尝试获取密度图以显示计数占每个方面总数的百分比。
例如,我有这个密度图:
由此代码生成:
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
我希望列显示:
- 第 1 列 = 350/3760 = 9%
- 第 2 列 = 950/3760 = 25%%
- 第 3 列 = 1630/3760 = 43%
- 第 4 列 = 630/3760 = 17%
- 第 5 列 = 200/3760 = 5%
我尝试使用 aes(y='..count../sum(..count..)')
,但这让我计算了 整个人口 ,而不是每个方面 人口 .
请帮忙。
使用aes(y=stat(width*density))
.
从 R 的 ggplot2 上的 post 得到了灵感,这是 plotnine 的基础。
https://github.com/tidyverse/ggplot2/issues/2499
我正在尝试获取密度图以显示计数占每个方面总数的百分比。
例如,我有这个密度图:
由此代码生成:
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 我希望列显示:
- 第 1 列 = 350/3760 = 9%
- 第 2 列 = 950/3760 = 25%%
- 第 3 列 = 1630/3760 = 43%
- 第 4 列 = 630/3760 = 17%
- 第 5 列 = 200/3760 = 5%
我尝试使用 aes(y='..count../sum(..count..)')
,但这让我计算了 整个人口 ,而不是每个方面 人口 .
请帮忙。
使用aes(y=stat(width*density))
.
从 R 的 ggplot2 上的 post 得到了灵感,这是 plotnine 的基础。 https://github.com/tidyverse/ggplot2/issues/2499