首页 > 解决方案 > 有没有办法在 Python 的散点图中对颜色使用条件?

问题描述

所以我是数据科学领域的新手,问题是我有一个数据集练习,所以我想做的是:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

file = pd.read_csv('datasets/office_episodes.csv')

x = np.array(file.loc[:,'episode_number'])

y = np.array(file.loc[:, 'viewership_mil'])

scaled_ratings = np.array(file.loc[:, 'scaled_ratings'])

ratings2 = list(scaled_ratings)
   
plt.title("Popularity, Quality, and Guest Appearances on the Office")

plt.xlabel("Episode Number")

plt.ylabel("Viewership (Millions)")

for i in ratings2:
    if i < 0.25:
         plt.scatter(x, y, c='red')
    elif i >=0.25 and i < 0.50:
          plt.scatter(x, y, c='orange')   
    elif i >= 0.50 and i < 0.75:
        plt.scatter(x, y, c='lightgreen')
    elif i >= 0.75:
        plt.scatter(x, y, c='darkgreen')
    else:
        plt.scatter(x, y, c='pink')


plt.show()

正如您在for 循环中看到的那样,我根据比例等级调节散点图中点的颜色,但是当显示图时,它看起来像这样:

图片

我还尝试创建一个名为rating3的变量,其中包含 rating2,这样我就可以进行列表理解,这样我就可以在plt.scatter( ) 函数的颜色参数中传递rating3 。

标签: pythonpandasnumpymatplotlib

解决方案


我不是这方面的专家,但这是我的解决方案。您首先必须为每个类别制作单独的数组。然后你可以用选择的颜色绘制每个。

y1 = np.array(file.loc[file['scaled_ratings'] < 0.25, 'viewership_mil'])
y2 = np.array(file.loc[0.25 <= file['scaled_ratings'] < 0.5, 'viewership_mil'])
y3 = np.array(file.loc[0.5 <= file['scaled_ratings'] < 0.75, 'viewership_mil'])
y4 = np.array(file.loc[0.75 <= file['scaled_ratings'], 'viewership_mil'])

plt.scatter(x, y1, c='red')
plt.scatter(x, y2, c='orange')
plt.scatter(x, y3, c='lightgreen')
plt.scatter(x, y4, c='darkgreen')

推荐阅读