You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用matplotlib绘制分类X轴散点图并按第三变量设置标记颜色

实现步骤及完整代码

前置依赖

确保已经安装pandas和matplotlib库,导入方式如下:

import pandas as pd
import matplotlib.pyplot as plt

步骤1:预处理数据集

先将数据集读取为pandas DataFrame(假设变量名为df),按Order列排序保证X轴展示顺序符合要求:

# 读取数据集,实际使用时根据文件格式调整读取方法,csv文件用pd.read_csv
# df = pd.read_csv("你的数据集文件路径")
# 按Order列升序排列,确定X轴展示顺序
df_sorted = df.sort_values(by="Order", ascending=True).reset_index(drop=True)

步骤2:构建类型到颜色的映射

给每个genre(电影类型)分配唯一颜色,用于后续散点着色:

# 提取所有唯一的电影类型
unique_genres = df_sorted["genre"].unique()
# 选择配色方案,可替换为Set2、viridis等matplotlib支持的其他colormap
cmap = plt.cm.get_cmap("tab10", len(unique_genres))
# 生成 类型-颜色 映射字典
genre_color_map = {genre: cmap(idx) for idx, genre in enumerate(unique_genres)}

步骤3:面向对象方式绘制散点图

严格使用指定的fig, ax = plt.subplots()初始化方式实现:

# 初始化绘图对象,可调整figsize适配标签长度
fig, ax = plt.subplots(figsize=(12, 6)) 

# 生成X轴数值坐标,后续替换为电影名称标签
x_coords = range(len(df_sorted))
# 注意:此处y列请替换为实际要展示的数值列,比如评分、票房等,示例用rating指代
y_values = df_sorted["rating"]
# 映射散点颜色
point_colors = df_sorted["genre"].map(genre_color_map)

# 绘制散点图,s为点大小、alpha为透明度,可自行调整
ax.scatter(x=x_coords, y=y_values, c=point_colors, s=80, alpha=0.8)

# 替换X轴刻度为电影名称,rotation旋转标签避免重叠,ha='right'保证标签对齐
ax.set_xticks(x_coords)
ax.set_xticklabels(df_sorted["movie_title"], rotation=45, ha="right")

# 添加图例
handles = [plt.Line2D([0], [0], marker="o", color="w", 
                      markerfacecolor=genre_color_map[g], 
                      markersize=10, label=g) for g in unique_genres]
ax.legend(handles=handles, title="电影类型")

# 自定义坐标轴和标题,可按需修改内容
ax.set_xlabel("电影名称")
ax.set_ylabel("你要展示的Y轴指标(如评分/票房)")
ax.set_title("不同类型电影的指标散点分布")

# 自动调整布局避免标签被截断
plt.tight_layout()
# 展示图像
plt.show()

可选调整项

  • 若X轴电影名称过长,可调大figsize的宽度参数,或者增大rotation的旋转角度
  • 可更换get_cmap里的配色方案,选择适配需求的配色
  • 散点的大小s、透明度alpha可根据实际展示效果调整

内容的提问来源于stack exchange,提问作者Yudkowsky90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:54:07