简体   繁体   中英

How to create horizontal histogram in Python's plotnine?

I'm using plotnine recently and wanted to plot a horizontal histogram (ie, a histogram with horizontal bars).

The following example illustrates the vertical histogram:

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)
)

And the result:

在此处输入图像描述

Simply changing the axes in aes doesn't work:

(
    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.'

How can I achieve the desired result?

Use coord_flip to achieve the desired result:

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()
)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM