简体   繁体   中英

IndexError: list assignment index out of range (Matplotlib)

So My idea was to create like labels along the bottom, where it goes "Day 1, Day 2, Day 3..." I thought maybe I could do it in a range instead of writing separate labels, but I tried the separate labels method and says the error(See Fig 1), the whole code is in (Fig 2)

The error that it raises (Fig 1)

Traceback (most recent call last):
  File "C:/Users/willi/AppData/Local/Programs/Python/Python38-32/kjhj.py", line 20, in <module>
    labels[6] = 'Day 5'
IndexError: list assignment index out of range

Here is the code: (Fig 2)

from numpy import *
import math
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

fig, ax = plt.subplots()
a = [20, 40, 60, 78, 90, 120, 220, 300, 400]
b = [40, 80, 90, 200, 400, 500, 600, 780, 900]

orange_patch = mpatches.Patch(color='orange', label='Orange Label')
plt.legend(handles=[orange_patch])
fig.canvas.draw()

labels = [item.get_text() for item in ax.get_xticklabels()]
labels[1] = 'Day 0'
labels[2] = 'Day 1'
labels[3] = 'Day 2'
labels[4] = 'Day 3'
labels[5] = 'Day 4'
labels[6] = 'Day 5'
ax.set_xticklabels(labels)
plt.plot(a)
plt.plot(b)
plt.show()


Much Appreciated!

Indices in Python starts from 0 and not 1. If you replace your code as such it should work:

labels[0] = 'Day 0'
labels[1] = 'Day 1'
labels[2] = 'Day 2'
labels[3] = 'Day 3'
labels[4] = 'Day 4'
labels[5] = 'Day 5'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM