How to use matplotlib to plot complex bar graphs–multiple subplots with multiple rows of bars?

Viewed 124

I have a sample dataframe like the following:

import pandas as pd

df = pd.DataFrame(np.random.randint(
    0, 10, size=(1000, 11)), columns=list('ABCDEFGHIJK'))

The desired but unpolished output looks like this:

The data of each column in the dataframe is plotted as a subplot with five rows of bars.

enter image description here

I prefer to use matplotlib because I can relatively easily make the graphs looking good. But its performance seems pretty slow.

1 Answers

You can use the bottom parameter of bar to offset the individual rows.
The following not optimized example demonstrates this approach:

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

df = pd.DataFrame(np.random.randint(0, 10, size=(1000, 11)), columns=list('ABCDEFGHIJK'))

fig = plt.figure()

for i,c in enumerate(df.columns):
    ax = fig.add_subplot(3, 4, i+1)
    for x,h,b in zip((df.index.to_numpy() % 200).reshape(-1, 200), df[c].to_numpy().reshape(-1, 200), (df.index.to_numpy() // 200 * 10).reshape(-1, 200)):
        ax.set_title(c)
        ax.bar(x, h, bottom=b, color='k' )

enter image description here

Related