Python Forum

Full Version: Matplotlib graphing help (dual y axis, groupby, filter)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I'm new to python and I'm trying to plot some graphs.

I'm trying to plot multiple series of numerical data that are defined by an ID column. For reference it is environmental data at different site locations, so one column is the value and another column is the site ID. I've posted some code below using simple dummy data, I've just adapted it from a tutorial.

I want to use .groupby('A1') and have 2 different data series plotted, but I can't figure out where in the code to use the .groupby?

I would also like to be able to filter by column A1, to be able to show any combination of X,Y,Z values. In my real data I have many series and I want to be able to plot different combinations of them.

I also want to be able to filter by the index, in my real data the index is the date, so I'd like to be able to filter by date and by column A1.

For instance something like dfA[1:2] and dfA.A1 == "X" (or ideally an array of what I want to filter) and dfA.groupby['A1'] all working together.

I'm just having issues to get all this working at the same time. Any help would be appreciated!

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.style as style
import matplotlib.dates as mdates
from datetime import datetime

A = {'Aindex': [1, 2, 3,1,2,3], 'A1': ['X', 'X', 'X','Y','Y','Y'], 'A2': [20,30,40,40,30,20]}
B = {'Bindex': [1, 2, 3], 'B1': [3, 3, 3]}

dfA = pd.DataFrame(data=A)
dfB = pd.DataFrame(data=B)

dfA.set_index('Aindex', inplace=True)
dfB.set_index('Bindex', inplace=True)

datay1 = dfA.A2
datay2 = dfB.B1
datax1 = dfA.index
datax2 = dfB.index

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('x')
ax1.set_ylabel('y1', color=color)
ax1.plot(datax1, datay1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('y2', color=color)  # we already handled the x-label with ax1
ax2.plot(datax2, datay2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()