python导入数据画多列直方图,如何在Python中绘制多个级别的groupby直方图?

I have a dataframe like this,

col1 col2 col3

A east 5

A west 7

A east 1

A east 6

B east 2

B west 9

B east 8

...

Z west 4

I know how to groupby and made histogram by using

df[df.col1.isin(ix)].groupby('col1').hist()

How can I get a 2 levels groupby and draw histograms by using the dataframe above?

For each col1 group histogram I want them in a separate plot. But for each col2 group. I hope them in one like this.

057e7dac401e411619b15a65e202ff8b.png

For example, the final results will be 26 histograms from A-Z. Each inside has 2 plots(east&west).

解决方案pandas.DataFrame.sort_values on col1 will also order the plot sequence from A to Z

Data:

import string

import numpy as np

import pandas as pd

import random

alpha_list = [random.choice(list(string.ascii_uppercase)) for _ in range(10_000)]

coor_list = [random.choice(['east', 'west']) for _ in range(10_000)]

rand_val = [np.random.randint(10) for _ in range(10_000)]

df = pd.DataFrame({'col1': alpha_list, 'col2': coor_list, 'col3': rand_val})

df.sort_values(by='col1', inplace=True)

col1 col2 col3

A west 1

A east 3

A west 9

A west 5

A west 7

A east 1

A east 5

A west 2

A east 2

A west 2

Plot:

g = sns.FacetGrid(df, col='col1', hue='col2', col_wrap=7)

g.map(sns.distplot, 'col3', hist_kws=dict(edgecolor='black'), bins=range(0, 11, 1), kde=False)

plt.xlabel('Value Range')

plt.ylabel('Frequency')

plt.legend()

plt.xticks(range(1, 11, 1))

plt.show()

1MUyF.png

if you want tick labels on each graph, put the following code on the line before plt.show():

for ax in g.axes.flatten():

ax.tick_params(labelbottom=True)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值