pandas 的两级分组地块 [英] Two level grouped plots in pandas

查看:77
本文介绍了 pandas 的两级分组地块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Python matplotlib和/或熊猫创建两级分组的条形图(即x轴上的组).

Is there any way to create a two level grouped bar chart (i.e. groups on the x-axis) using Python matplotlib and / or pandas.

显示我的意思的示例

推荐答案

显然,这是在愿望清单. 这是示例,该示例在您的文章中引用了该示例,它具有您想要的功能,但具有几个功能.

Apparently this is on the wishlist. Here's an example that is referred to in the post that does what you want, but with a couple of functions.

但是,一种快速的解决方案是仅并排绘制两个条形图,然后对图形进行一些自定义.

However, a quick solution would be to just plot two bar plots side-by-side and customising the graph a little bit.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

#create multindex dataframe
arrays = [['Fruit', 'Fruit', 'Fruit', 'Veggies', 'Veggies', 'Veggies'],
          ['Bananas', 'Oranges', 'Pears', 'Carrots', 'Potatoes', 'Celery']]
index = pd.MultiIndex.from_tuples(list(zip(*arrays)))
df = pd.DataFrame(np.random.randint(10, 50, size=(1, 6)), columns=index)

#plotting
fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(14 / 2.54, 10 / 2.54))  # width, height
for i, col in enumerate(df.columns.levels[0]):
    print(col)
    ax = axes[i]
    df[col].T.plot(ax=ax, kind='bar', width=.8)

    ax.legend_.remove()
    ax.set_xlabel(col, weight='bold')
    ax.yaxis.grid(b=True, which='major', color='black', linestyle='--', alpha=.4)
    ax.set_axisbelow(True)

    for tick in ax.get_xticklabels():
        tick.set_rotation(0)

#make the ticklines invisible
ax.tick_params(axis=u'both', which=u'both', length=0)
plt.tight_layout()
# remove spacing in between
fig.subplots_adjust(wspace=0)  # space between plots

plt.show()

这篇关于 pandas 的两级分组地块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆