简体   繁体   English

如何修复 Python 散点图中的“列表索引超出范围”错误?

[英]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.

相关问题 如何在python 3.4 tkinter中修复此错误“索引错误:列表索引超出范围” - How can I fix this error in python 3.4 tkinter “Index Error: list index out of range” 动画线和散点图时如何避免“列表索引超出范围”错误 - How do I avoid the 'list index out of range' error when animating line as well as scatter plot 在python中如何修复列表索引超出范围的问题? - In python how can i fix list index out of range problem? 如何解决此错误:IndexError:列表索引超出范围 - How can I fix this error: IndexError: list index out of range 我该如何解决这个错误,它说列表索引超出范围? - How can i fix this error it says the list index is out of range? 我该如何解决这个列表问题(列表索引超出范围) - How can I fix this list problem (list index out of range) 如何解决我的代码错误“列表索引超出范围” - How to fix my code's error “List index out of range” 如何修复Python中的“列表索引超出范围”错误? - How to fix 'list index out of range' error in python? 如何修复Python中的``列表索引超出范围''错误 - How to fix 'list index out of range' error in python 如何修复Python中的“ IndexError:列表分配索引超出范围”错误? - How to fix “IndexError: list assignment index out of range” error in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM