具有多个 y 轴的 pandas/matplotlib 图

1 python matplotlib pandas

我有一个 DataFrame 如下:

                                   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
Run Code Online (Sandbox Code Playgroud)

我已经多次尝试使用对应于右两列的两个 y 轴进行绘图,最左边的列是 x 轴。但到目前为止,我只设法为两者获得了一个轴。我试图在这里模仿解决方案:http : //matplotlib.org/examples/api/two_scales.html但我一直失败。我还查看了其他 stackoverflow Q&S,但到目前为止还没有发现它们很清楚。如果有人能帮我解决这个问题,那就太好了。干杯。

Ell*_*iot 5

你真的应该包括你尝试过的代码片段,这样人们才能真正为你指明正确的方向。尽管如此,我猜你已经错过了,pandas除非你指定一个预先存在的轴来绘制,否则会打开一个新的图形和新的轴对象。

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()
Run Code Online (Sandbox Code Playgroud)

您需要更多地使用它才能获得好看的情节,但这应该可以让您开始。