python - 有没有办法在 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 。
解决方案
我不是这方面的专家,但这是我的解决方案。您首先必须为每个类别制作单独的数组。然后你可以用选择的颜色绘制每个。
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')
推荐阅读
- android - 如何通过在 Firebase 实时数据库中使用 ServerValue.increment() 来施加限制?
- javascript - 配置prism.js识别
标签(没有
tag)
- rust - 为什么在 rust rocket_contrib 时“服务中没有 crate_relative”?
- terratest - 如何使用 terraTest 列出所有现有 VM
- pandas - 如何将由不规则、混合格式的数据和混合分隔符组成的 csv 文件加载到数据框中?
- dockerfile - Visual Studio 生成的 Dockerfile 奇怪路径
- reactjs - 如何在打字稿类型定义中使用常量?
- c# - 调整可序列化列表大小(Unity C#)
- if-statement - 如何使用 If 和 listBox1.SelectedItem 更改图片框
- hash - 在 Java 中使用 Redisson 在 Redis 中创建 SQL 类型表的任何替代解决方案