【问题标题】:Python Matplotlib - how to use Axes.plot() method inside for loopsPython Matplotlib - 如何在 for 循环中使用 Axes.plot() 方法
【发布时间】:2020-03-25 20:42:57
【问题描述】:

我正在尝试使用 axes.plot() 方法绘制一个简单的多系列折线图,我需要在 for 循环内将数据传递给 axes.plot()。程序设置如下:

def Plot(dict_inner):
    df = pd.DataFrame.from_dict(dict_inner)
    cases = df.columns.values.tolist()
    fig, ax = plt.subplots()
    x = df['Date']
    for case in cases:
        y = df[case]
        ax.plot(x, y)
    plt.legend()
    plt.show()

这将返回各种matplotlib 方法的错误列表,以: ValueError:视图限制最小值 -36502.7149864 小于 1,并且是无效的 Matplotlib 日期值。如果您将非日期时间值传递给具有日期时间单位的轴,通常会发生这种情况 ts

但是,如果在 for 循环之外调用该方法,如下所示,我可以生成绘图:

def Plot(dict_inner):
    df = pd.DataFrame.from_dict(dict_inner)
    fig, ax = plt.subplots()
    x = df['Date']
    case_1 = '3xKd'
    case_2 = '9xKd'
    y1 = df[case_1]
    y2 = df[case_2]
    ax.plot(x, y1)
    ax.plot(x, y2)
    plt.legend()
    plt.show()

我是 Python 新手,如果有任何帮助,我将不胜感激。谢谢!

【问题讨论】:

  • print(cases) 以查看您不想在 y 轴上绘制的列名。
  • ax.plot(x, y)hold(True)之后使用
  • 我试过 ax.plot(x, y).hold(True) 但返回 AttributeError: 'list object has no attribute 'hold'。
  • @ImportanceOfBeingErnest 是的,就是这样。 “日期”是案例中的列之一,这就是问题所在。刚刚在 for 循环中添加了一个 if 语句,仅当大小写不等于“日期”时才绘制。谢谢!

标签: python matplotlib


【解决方案1】:
import matplotlib.pyplot as plt
fig = plt.figure()
plot_this =  fig.add_subplot()

for colour in ['red','blue','green']:
    x= np.random.rand(6,1)
    y=np.random.rand(6,1)
    plot_this.plot(x, y, color=colour)

plt.show()

我以前遇到过类似的事情。 在这种情况下,我使用 add_subplot(),创建一个新对象并从那里绘图。 希望这会有所帮助。

【讨论】:

  • 我按照你的建议设置了脚本,在 for 循环外有“fig=plt.figure()”和“plot_this=fig.add_subplot()”,然后在里面设置了 x 和 y循环并传递到“plot_this.plot(x,y”。这将返回以下错误:plot_this.plot(x, y) AttributeError: 'NoneType' object has no attribute 'plot'。我应该提到 matplotlib.pylot导入,我使用的是 Python 2.7。
  • 我明白了。好的,你可以试试这个link 建议的解决方案
猜你喜欢
  • 1970-01-01
  • 2017-09-14
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多