1

I have a python script that has 3 functions that plot data. 2 of them show gridlines by using ax.grid(b=True). One however, doesn't. Even after I spammed ax.grid(b=True) all over the place... I must be doing something wrong, but what?

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

Maybe it has something to do with plt.ion() ? Because I don't have that in the othe plotting functions that do show the grid.

I already tried this and this by adding the plt.minorticks_on(), but to no avail sadly.

Is there something obvious I'm missing? Or is there some other hidden incompatibility?

Screenshot of plot as requested: enter image description here

Opifex
  • 362
  • 4
  • 15

2 Answers2

2

Add in a call to plt.grid() inside your function, and remove extraneous code:

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)

This code generates a plot and dynamically updates it, all while showing the gridlines the whole time.

Plot with gridlines

Nathaniel
  • 3,230
  • 11
  • 18
  • I'm not sure what kind of functionality you're trying to get out of ``plt.ion()``, but this code will give you the gridlines successfully. – Nathaniel Mar 25 '19 at 21:17
  • plt.ion() is used to make plt.plot() non-blocking. It allows my script to continously run, and update the graph after each iteration. Strangely enough, your code only seems to work with the last iteration of my script. – Opifex Mar 25 '19 at 21:53
  • I have updated my answer to try and address this. Since I cannot run your code in a loop like you seem to be using it, I can't test it for that specific case. Can you please update your question to include the iteration loop you speak of? – Nathaniel Mar 25 '19 at 22:00
  • @Opifex I have added an example loop which shows dynamic plotting of the data. Please let me know if this adequately addresses your question. – Nathaniel Mar 25 '19 at 22:07
  • I used your original answer, and did some tinkering and finally got it working. I moved clf() to the top of the function, and grid() right below subplots(). This seems to have fixed it (or I did something else while tinkering that solved it). I'm not sure whose answer to accept now though, because Meng's was also correct in a way (even though it didn't work for my purpose), but more importantly: his remarks were very valuable I think. – Opifex Mar 25 '19 at 22:08
  • I'm glad to hear it is working for you now. You can upvote any answers that were helpful, and accept the one that answers your question best. – Nathaniel Mar 25 '19 at 22:15
1

I think you have some unnecessary codes, which creates multiple plots. The first plot you had is empty but with grids and the later plots contain the data, but not the grids.

Try the code below. I commented some of your scripts and made it work.

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(times, bestScores, '-', label="best score") # you can change it back to plot_date
    plot = plt.setp(plot, color='y', linewidth=1.0)
    plot = plt.plot(times, scores, '-', label="score") # you can change it back to plot_date
    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')

times = list(range(0,100))
bestScores = list(range(100,200))
scores = list(range(150,250))
xsplit=0
window=1
plotMSEProgress(times, bestScores, scores, xsplit=0, window=1)

enter image description here

Community
  • 1
  • 1
Meng
  • 1,148
  • 5
  • 15
  • 23
  • I tried your code and it seems to work, but when it gets redrawn, the previous plot doesn't dissapear. It seems like it is overlayed on eachother. see: http://imagehost.cc/image/k20gS I tried re-adding plt.clf(), but then the grid also dissapears again? =/ Any clue how I would fix this? – Opifex Mar 25 '19 at 21:43