Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

python - Two level grouped plots in pandas

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.

An example of what I mean is shown here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...