IndexError:列表赋值索引超出范围(Matplotlib)

所以我的想法是在底部创建类似的标签,它是“第 1 天、第 2 天、第 3 天......”我想也许我可以在一个范围内做而不是写单独的标签,但我尝试了单独的标签方法并说出错误(见图1),整个代码在(图2)


它引发的错误(图 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

这是代码:(图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()



非常感激!


Cats萌萌
浏览 135回答 1
1回答

阿波罗的战车

Python 中的索引从 0 而不是 1 开始。如果您这样替换代码,它应该可以工作:labels[0] = 'Day 0'labels[1] = 'Day 1'labels[2] = 'Day 2'labels[3] = 'Day 3'labels[4] = 'Day 4'labels[5] = 'Day 5'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python