简体   繁体   中英

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] . You have used i to iterate over the length of view_count column. Instead try using a separate iterator for indexing colors list which iterates over the len of colors list.

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

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