Pandas DataFrames and Grouped Data
As we learned in the previous chapter, when analyzing data and using Pandas to do so, we can use the plot functions from Pandas or use Matplotlib directly. Pandas uses Matplotlib under the hood, so the integration is great. Depending on the situation, we can either plot directly from pandas or create a figure and an axes with Matplotlib and pass it to pandas to plot. For example, when doing a GroupBy, we can separate the data into a GroupBy key. But how can we plot the results of GroupBy? We have a few approaches at our disposal. We can, for example, use pandas directly, if the DataFrame is already in the right format:
Note
The following code is a sample and will not get executed.
fig, ax = plt.subplots() df = pd.read_csv('data/dow_jones_index.data') df[df.stock.isin(['MSFT', 'GE', 'PG'])].groupby('stock')['volume'].plot(ax=ax)
Or we can just plot each GroupBy key on the same plot:
fig, ax = plt.subplots() df.groupby('stock').volume.plot(ax=ax)
For the following...