首页 > 解决方案 > Python 3D 散点图 - 使用分类变量调整颜色

问题描述

我正在尝试为电影数据集制作 3D 散点图。我想根据电影的类型调整颜色。我有 5 种类型,我想制作喜剧红色、动作蓝色、冒险绿色等。

使用此代码,我只能制作黄色和红色。我怎样才能制作所有这些?

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
import numpy as np
import seaborn as sns

movies = pd.read_csv(r'C:\...\movies.csv', nrows = 400)

fig = plt.figure(figsize=(8, 6))
t = fig.suptitle('Wine Residual Sugar - Alcohol Content - Acidity - Type', fontsize=14)
ax = fig.add_subplot(111, projection='3d')

xs = list(movies['gross'])
ys = list(movies['budget'])
zs = list(movies['score'])
data_points = [(x, y, z) for x, y, z in zip(xs, ys, zs)]
colors = ['red' if gt == 'Comedy' else 'yellow' for gt in list(movies['genre'])]

for data, color in zip(data_points, colors):
   x, y, z = data
   ax.scatter(x, y, z, alpha=0.4, c=color, edgecolors='none', s=30)

 ax.set_xlabel('gross')
 ax.set_ylabel('budget')
 ax.set_zlabel('score')

标签: pythoncolorsdata-visualizationscatter-plotscatter3d

解决方案


定义一个字典,其中键是流派,值是颜色,然后制作colors= [dict[i] for i in list(movies['genre'])]


推荐阅读