0

I am trying to plot a simple multi-series line chart using the axes.plot() method whereby I need to pass the data to axes.plot() inside a for loop. The program is set up as follows:

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

This returns a list of errors for various matplotlib methods, ending with: ValueError: view limit minimum -36502.7149864 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime uni ts

However, if the method is called outside the for loop as follows I am able to generate the plot:

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

enter image description here

I am new to Python and would appreciate any help. Thanks!

4
  • print(cases) to see that there are column names which you don't want to plot on the y axes. Commented Nov 30, 2019 at 17:37
  • use after ax.plot(x, y) hold(True) Commented Nov 30, 2019 at 19:09
  • I tried ax.plot(x, y).hold(True) but returns AttributeError: 'list object has no attribute 'hold'. Commented Dec 2, 2019 at 14:00
  • @ImportanceOfBeingErnest yup that was it. 'Date' was one of the columns in cases and that was the issue. Just added an if statement inside the for loop to plot only when case not equal to 'Date'. Thank! Commented Dec 2, 2019 at 15:27

1 Answer 1

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

I faced something similar before. I use add_subplot() in this case, create a new object and plot from there. Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

I set up the script as you suggested where I have "fig=plt.figure()" and "plot_this=fig.add_subplot()" outside the for loop and then x and y are set inside the loop and passed into "plot_this.plot(x,y". This is returning the following error: plot_this.plot(x, y) AttributeError: 'NoneType' object has no attribute 'plot'. I should mention have matplotlib.pylot imported and I'm using Python 2.7.
I see. Alright, may you can try the solution suggested by this link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.