如何在 Python 的 plotnine 中创建水平直方图?

How to create horizontal histogram in Python's plotnine?

我最近在使用 plotnine,想绘制水平直方图(即带有水平条的直方图)。

下例说明了垂直直方图:

from plotnine import *
import numpy as np

df = pd.DataFrame({'values': np.random.normal(0,10,1000), 'group': ['a']*500 + ['b']*500})
# 
(
    ggplot(df, aes(x = 'values', y = after_stat('count'), fill = 'group'))
    + geom_histogram(binwidth = 5)
)

结果:

简单地改变 aes 中的坐标轴是行不通的:

(
    ggplot(df, aes(y = 'values', x = after_stat('count'), fill = 'group'))
    + geom_histogram(binwidth = 5)
)
#PlotnineError: 'stat_bin() must not be used with a y aesthetic.'

怎样才能达到预期的效果?

使用coord_flip达到预期效果:

from plotnine import *
import numpy as np

df = pd.DataFrame({'values': np.random.normal(0,10,1000), 'group': ['a']*500 + ['b']*500})
# 
(
    ggplot(df, aes(x = 'values', y = after_stat('count'), fill = 'group'))
    + geom_histogram(binwidth = 5)
    + coord_flip()
)