使用pandas.plot绘图结果为空

3 投票
1 回答
4840 浏览
提问于 2025-04-18 13:40

我正在尝试绘制一个需要两个y轴的图表。我可以用一个y轴成功绘图,但当我使用两个y轴时,图表却是空的。我试过把数据分成两个不同的数据框,也试过不分开,但都没有成功。

我现在的代码是:

    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")

运行这个代码的结果是一个空的图表。

我的代码哪里出错了呢?

1 个回答

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()

撰写回答