[英]How can I fix "list index out of range" error in my scatter plot on Python?
Can you take a look at my code and tell me the reason why I receive 'list index out of range' error?你能看看我的代码并告诉我为什么我收到“列表索引超出范围”错误的原因吗?
fig, ax = plt.subplots(figsize=(10,5))
view_count = dodo_data['view_count']
like_count = dodo_data['like_count']
colors = ['r', 'k', 'b', 'g']
ax.legend()
ax.set_xlabel('View Count')
ax.set_ylabel('Like Count', rotation=0, labelpad=55)
for i in range(len(view_count)):
plt.plot(view_count[i], like_count[i], 'o', color=colors[i])
The problem is with the colors[i]
.问题出在
colors[i]
上。 You have used i
to iterate over the length of view_count
column.您已使用
i
遍历view_count
列的长度。 Instead try using a separate iterator for indexing colors
list which iterates over the len
of colors
list.而是尝试使用单独的迭代器来索引
colors
列表,该迭代器len
colors
列表的长度。
I've tried with a sample data, which I'm posting below.我已经尝试使用我在下面发布的示例数据。 Hope it helps!!
希望能帮助到你!!
from pandas import DataFrame
Data = {'view_count': [1,2,3,4,5],
'like_count': [6,7,8,9,10],
}
dodo_data = DataFrame (Data, columns = ['view_count','like_count'])
print(dodo_data)
import matplotlib.pyplot as plt
import random
fig, ax = plt.subplots(figsize=(10,5))
view_count = dodo_data['view_count']
like_count = dodo_data['like_count']
colors = ['r', 'k', 'b', 'g']
ax.legend()
ax.set_xlabel('View Count')
ax.set_ylabel('Like Count', rotation=0, labelpad=55)
for i in range(len(view_count)):
plt.plot(view_count[i], like_count[i], 'o', color=colors[random.sample(range(len(colors)),1)[0]])
You can do this:你可以这样做:
for i in range(len(view_count)):
plt.plot(view_count[i], like_count[i], 'o', color=colors[i%4])
You'll get output like this:你会得到这样的输出:
1 6 r
2 7 k
3 8 b
4 9 g
5 10 r
6 2 k
7 3 b
8 4 g
9 5 r
34 4 k
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.