Hadiii
Hadiii

Reputation: 11

pandas/matplotlib plot with multiple y axes

I have a DataFrame as below:

                                   Rate per 100,000 population  Gambling EXP per Adult
Local Government Area                                                     
City of Banyule                             7587.7              555.188876
City of Bayside                             5189.9              171.282451
City of Boroondara                          4877.0              141.675636
City of Brimbank                            9739.0              904.959407
City of Casey                               7790.6              561.086313

I have made several attempts at plotting with the two y-axes corresponding to right two columns with the left most column being the x-axis. But so far I have only managed to get one axes for both. I have tried to mimic the solution here: http://matplotlib.org/examples/api/two_scales.html but I keep failing. I have also looked at other stackoverflow Q&S but haven't found them very clear so far. Would be great if someone could help me solve this problem. Cheers.

Upvotes: 1

Views: 4393

Answers (1)

Elliot
Elliot

Reputation: 2690

You really should include the code snipped that you tried so that people can actually point you in the right direction. Nonetheless, I'm guessing that you've missed that pandas will open a new figure and new axis object unless you specify a preexisting axis to plot with.

import pandas as pd
import matplotlib.pyplot as plt

# separate data file
dat = pd.read_csv('dat.csv', index_col='Local Government Area')

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

# the ax keyword sets the axis that the data frame plots to
dat.plot(ax=ax1, y='Rate per 100 000 population', legend=False)
dat.plot(ax=ax2, y='Gambling EXP per Adult', legend=False, color='g')
ax1.set_ylabel('Rate per 100,000 population')
ax2.set_ylabel('Gambling EXP per Adult')
plt.show()

You'll need to futz with it more to get a good looking plot, but that should get you started.

Upvotes: 5

Related Questions