本文介绍了用 pandas.plot 出来的图是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制一个必须有两个 y 轴的 df.我可以只使用一个轴就可以使绘图工作,但是当我使用两个轴时,它会显示为空.我试过分成两个单独的数据帧,同样没有这样做,但都没有工作.

I am trying to plot a df that must have two y-axes. I can get the plot to work using only one axis, but when I use two it comes out empty. I've tried separating into two separate dataframes and equally not doing this but neither is working.

我目前的代码:

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

这样做的结果是一个空图.

The result of this is an empty plot.

我的代码有什么错误?

推荐答案

看起来您明确地将它们绘制在相同的轴上.您已经创建了一个新图形和一个名为 ax2 的第二个轴,但是您正在通过调用 df2.plot(..., ax=ax) 在第一个轴上绘制第二个数据框 而不是 df2.plot(..., ax=ax2)

It looks like you're explicitly plotting them both on the same axes. You've made a new figure and a second axes called ax2, but you're plotting the second dataframe on the first axes by calling df2.plot(..., ax=ax) instead of df2.plot(..., ax=ax2)

举一个简单的例子,你基本上是在做:

As a simplified example, you're basically doing:

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

当您想要更多类似的东西时:

When you want something more like:

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

这篇关于用 pandas.plot 出来的图是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:46