Reputation: 1102
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.
Upvotes: 4
Views: 12675
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
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()
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()
Upvotes: 6