如何根据世代显示,x'攻击'和y'防御'

2024-10-06 03:59:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个初学者。我无法按颜色分组按代显示图形。 世代共有6代

如果您看到图片,代码的结果是现在图形以一种颜色显示

import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("../input/pokemon/Pokemon.csv")
x = df['Attack']
y = df['Defense']
z = df['Generation']

tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),  
             (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),  
             (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),  
             (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),  
             (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]



for i in range(len(tableau20)):  
    r, g, b = tableau20[i]  
    tableau20[i] = (r / 255., g / 255., b / 255.)

colors = tableau20[::2]
f, ax = plt.subplots()
for i in np.unique(z):

    plt.scatter(x , y  , label=i , color=colors[i])

ax.legend()
plt.show()

我希望按生成按颜色分组显示图形:

enter image description here


Tags: csvinimport图形dffor颜色as
1条回答
网友
1楼 · 发布于 2024-10-06 03:59:29

对于代码中的每个i,您都在绘制整个数据集,因为您在代码的开头定义了x,y。一个快速解决方案是在与生成匹配的数据子集上定义x,y

for i in np.unique(z):

    #define x,y on the part of the df that matches the resp. Generation
    df2 = df[df['Generation']==i]       
    x = df2['Attack']
    y = df2['Defense']

    plt.scatter(x , y  , label=i , color=colors[i])

但是如果df['Generation']中的值是int,您也可以简单地执行以下操作:

cols = [colors[a] for a in df['Generation']]      
plt.scatter(df['Attack'], df['Defense'], c=cols)

相关问题 更多 >