首页 > 解决方案 > Pyplot 拒绝显示网格

问题描述

我有一个 python 脚本,它有 3 个绘制数据的函数。其中 2 个使用ax.grid(b=True)显示网格线。然而,一个没有。即使在我到处发送垃圾邮件 ax.grid(b=True) 之后......我一定是做错了什么,但是什么?

def plotMSEProgress(times, bestScores, scores, xsplit=0, window=1):
    plot, ax = plt.subplots(figsize=(20,10), num=1)
    ax.grid(b=True, which='both')

    # plot = plt.figure(window)
    plt.ion()
    plt.minorticks_on()
    ax.grid(b=True, which='both')

    plt.show()

    plt.clf()

    if xsplit:
        plt.axvline(x=xsplit, color='g')

    plot = plt.plot_date(times, bestScores, '-', label="best score")
    plot = plt.setp(plot, color='y', linewidth=1.0)
    plot = plt.plot_date(times, scores, '-', label="score")
    plot = plt.setp(plot, color='b', linewidth=1.0)

    ax.grid(b=True, which='both')
    plt.xlabel('time')
    plt.ylabel('MSE')
    plt.suptitle('MSE over time', fontsize=16)
    plt.legend()
    ax.grid(b=True, which='both')
    plt.draw()
    ax.grid(b=True, which='both')
    plt.pause(0.001)        
    ax.grid(b=True, which='both')
    plt.plot()
    ax.grid(b=True, which='both')

也许它与plt.ion() 有关?因为我在其他显示网格的绘图函数中没有它。

我已经通过添加plt.minorticks_on()尝试了这个这个,但遗憾的是无济于事。

我有什么明显的遗漏吗?还是有其他隐藏的不兼容?

根据要求的情节截图: 在此处输入图像描述

标签: pythonpython-3.xmatplotlib

解决方案


添加对plt.grid()函数内部的调用,并删除无关代码:

import matplotlib.pyplot as plt
import datetime

def plotMSEProgress(times, bestScores, scores, xsplit=0, window=1):
    plot, ax = plt.subplots(figsize=(20,10), num=1)

    plt.ion()    
    plt.clf()

    if xsplit:
        plt.axvline(x=xsplit, color='g')

    plot = plt.plot_date(times, bestScores, '-', label="best score")
    plot = plt.setp(plot, color='y', linewidth=1.0)
    plot = plt.plot_date(times, scores, '-', label="score")
    plot = plt.setp(plot, color='b', linewidth=1.0)

    plt.minorticks_on()
    plt.grid(which='major')
    plt.grid(which='minor', linestyle = ':')

    plt.xlabel('time')
    plt.ylabel('MSE')
    plt.suptitle('MSE over time', fontsize=16)
    plt.legend(loc=2)
    plt.draw()
    plt.pause(0.001)

# Generate example data
base = datetime.datetime.today()
times = [base + datetime.timedelta(seconds=x) for x in range(0, 100)]
scores = np.random.rand(len(times))*30
bestScores = np.random.rand(len(times))*5

# Generate plot dynamically
for i in range(len(times)):
    plotMSEProgress(times[0:i], bestScores[0:i], scores[0:i], xsplit=0, window=1)

此代码生成一个绘图并动态更新它,同时始终显示网格线。

用网格线绘制


推荐阅读