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

如何在Matplotlib循环绘制的散点图下方添加水平色条?

解决Pandas散点图水平色条(底部放置)的问题

直接修改你的代码,通过手动创建水平色条并调整布局来实现需求,具体代码如下:

import matplotlib.pyplot as plt
import pandas as pd

# 假设你的df数据框已定义完成
num_cols = df.columns.to_list()[:-1]

for col in num_cols:
    # 绘制散点图并获取坐标轴对象
    ax = df.plot.scatter(x=col, y=df.columns[-1], c=col, cmap='Paired', title=col, figsize=(5, 5))
    # 获取散点图的绘图集合元素
    scatter_collection = ax.collections[0]
    # 创建水平色条,设置方向为水平,pad控制色条与主图的间距
    plt.colorbar(scatter_collection, orientation='horizontal', pad=0.15, ax=ax)
    # 调整底部布局,避免色条被窗口截断
    plt.subplots_adjust(bottom=0.2)
    # 单独显示每张图
    plt.show()

关键说明:

  • Pandas的df.plot.scatter()默认生成垂直色条,没有直接参数修改方向,因此需要手动提取散点的绘图元素(ax.collections[0])来创建自定义色条。
  • orientation='horizontal'指定色条为水平方向,pad参数用来微调色条与主图的垂直间距,避免布局拥挤。
  • plt.subplots_adjust(bottom=0.2)为主图底部预留足够空间,防止水平色条被窗口边缘截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:50:54