Python 带着熊猫出来的情节是空的
我试图绘制一个必须有两个y轴的df。我只能用一个轴来绘制,但当我用两个轴时,结果是空的。我尝试过将数据帧分成两个独立的数据帧,但同样不这样做,但两者都不起作用 我的代码当前为:Python 带着熊猫出来的情节是空的,python,matplotlib,plot,Python,Matplotlib,Plot,我试图绘制一个必须有两个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 a
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")
这样做的结果是一个空图
我的代码中有什么错误?看起来您在同一轴上显式地绘制它们。您已经创建了一个新图形和一个名为
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()
请不要给我们完整的代码,把它减少到我们可以复制的最小的例子。抱歉。现在已编辑。请给我们假数据,以便我们可以快速重现问题。确保你写的每一行都对我们有用。(例如,
colors=['b','g']
对我们有用吗?)此外,您可能会通过这样做自己发现问题。乍一看,您似乎在同一个轴上显式地绘制它们。(请注意,在两个调用中都有ax=ax
,而您调用了第二个轴ax2
)