我试图绘制一个必须有两个y轴的df。我可以使用一个轴来完成绘图,但是当我使用两个轴时,它会变空。我尝试分成两个独立的数据框,同样不这样做,但两者都没有。
目前我的代码:
df1 = A dataframe with two columns of data and a period index.
df2 = A dataframe with one column of data and a period index, to
plot on a separate axis .
colors = ['b', 'g']
styles = ['-', '-']
linewidths = [4,2]
fig, ax = plt.subplots()
for col, style, lw, color in zip(df1.columns, styles, linewidths, colors):
df1[col].plot(style=style, color=color, lw=lw, ax=ax)
plt.xlabel('Date')
plt.ylabel('First y axis label')
plt.hold()
colors2 = ['b']
styles2 = ['-']
fig2, ax2 = plt.subplots()
for col, style, lw, color in zip(df2.columns, styles, linewidths, colors):
df2.monthly_windspeed_to_plot[col].plot(style=style, color=color, lw=lw, ax=ax)
plt.ylabel('Second y axis label')
plt.title('A Title')
plt.legend(['Item 1', 'Item 2', 'Item 3'], loc='upper center',
bbox_to_anchor=(0.5, 1.05))
plt.savefig("My title.png")
结果是空图。
我的代码中有什么错误?
答案 0 :(得分:1)
看起来你是在同一轴上明确地绘制它们。您已经创建了一个名为ax2
的新图形和第二个轴,但是您通过调用df2.plot(..., ax=ax)
而不是df2.plot(..., ax=ax2)
来绘制第一个轴上的第二个数据帧
作为简化示例,您基本上在做:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Generate some placeholder data
df1 = pd.DataFrame(np.random.random(10))
df2 = pd.DataFrame(np.random.random(10))
fig, ax = plt.subplots()
df1.plot(ax=ax)
fig, ax2 = plt.subplots()
df2.plot(ax=ax)
plt.show()
当你想要更像的东西时:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Generate some placeholder data
df1 = pd.DataFrame(np.random.random(10))
df2 = pd.DataFrame(np.random.random(10))
fig, ax = plt.subplots()
df1.plot(ax=ax)
fig, ax2 = plt.subplots()
df2.plot(ax=ax2) # Note that I'm specifying the new axes object
plt.show()