5

Example Plot that needs to format date

I am trying to plot stock prices against time (see above). The code below does plot the "OPEN" prices but as I try to format the X-axis dates from ordinal to ISO dates, it throws AttributeError.

The same code worked while plotting the OHLC graph, but somehow this doesn't work now.

AttributeError: 'list' object has no attribute 'xaxis'

    df_copy = read_stock('EBAY')

    fig = plt.figure(figsize= (12,10), dpi = 80)
    ax1 = plt.subplot(111)
    ax1 = plt.plot(df_copy['Date'], df_copy['Open'], label = 'Open values' )
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
2
  • Try df_copy.set_index('Date').Open.plot(label='Open values') Commented Jan 22, 2018 at 6:49
  • That works! Thanks. However, my query remains. Why does it throw the error, specifying its a list? Commented Jan 22, 2018 at 6:54

2 Answers 2

6

This line:

ax1 = plt.plot(df_copy['Date'], df_copy['Open'], label='Open values')

Refines your Axes object to be the list of artists returned by the plot command.

Instead of relying on the state machine to put artists on the Axes, you should use your objects directly:

df_copy = read_stock('EBAY')

fig = plt.figure(figsize=(12, 10), dpi=80)
ax1 = fig.add_subplot(111)
lines = ax1.plot(df_copy['Date'], df_copy['Open'], label='Open values')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
Sign up to request clarification or add additional context in comments.

Comments

2

The problem comes from you writing

ax1 = plt.plot(df_copy['Date'], df_copy['Open'], label = 'Open values' )

Since you are changing the type of ax1 from being the handle returned by plt.subplot(). After said line, it is a list of lines that were added to the plot, which explains your error message. See the documentary on the plot command:

Return value is a list of lines that were added. matplotlib.org

Comments

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.