hot_whisky
hot_whisky

Reputation: 1102

Matplotlib: Plot multiple lines per time series subplot

Using subplots, is there a pythonic way to plot multiple lines per subplot? I have a pandas dataframe with two row indices, datestring and fruit, with store for columns and quantity for values. I want 5 subplots, one for each store, with datestring as the x-axis and quantity as the y axis, with each fruit as its own colored line.

df.plot(subplots=True)

Almost gets me there, I think, with the right amount of subplots, except it aggregates the quantities altogether rather than plotting by fruits.

enter image description here

Upvotes: 4

Views: 12675

Answers (1)

piRSquared
piRSquared

Reputation: 294218

setup
always provide sample data that reproduces your problem.
I've provided some here

cols = pd.Index(['TJ', 'WH', 'SAFE', 'Walmart', 'Generic'], name='Store')
dates = ['2015-10-23', '2015-10-24']
fruit = ['carrots', 'pears', 'mangos', 'banannas',
         'melons', 'strawberries', 'blueberries', 'blackberries']
rows = pd.MultiIndex.from_product([dates, fruit], names=['datestring', 'fruit'])
df = pd.DataFrame(np.random.randint(50, size=(16, 5)), rows, cols)
df

enter image description here

First, you want to convert that first level of the row index with pd.to_datetime

df.index.set_levels(pd.to_datetime(df.index.levels[0]), 0, inplace=True)

Now we can see that we can plot intuitively

# fill_value is unnecessary with the sample data, but should be there 
df.TJ.unstack(fill_value=0).plot()

enter image description here

We can plot all of them with

fig, axes = plt.subplots(5, 1, figsize=(12, 8))

for i, (j, col) in enumerate(df.iteritems()):
    ax = axes[i]
    col = col.rename_axis([None, None])
    col.unstack(fill_value=0).plot(ax=ax, title=j, legend=False)

    if i == 0:
        ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', ncol=1)

fig.tight_layout()

enter image description here

Upvotes: 6

Related Questions