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

如何为DataFrame不同列数据在Matplotlib绘图中设置不同颜色

解决方法

最简单的方式是给color参数传入一个颜色列表,对应每一列的颜色:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
         [
             [1, 1.0, 0.0, 0.0],
             [1, 0.75, 0.25, 0.0],
             [1, 0.576, 0.396, 0.028]
         ],
         columns = ["State", "1", "2", "3"]
    )

fig = plt.figure()
ax = plt.subplot()

# 传入颜色列表对应每一列的指定颜色
ax.plot(df[["1","2","3"]], label = ["1 (from 1)","2 (from 1)","3 (from 1)"], 
        color = ["red", "blue", "green"], marker = ".", linestyle="-")
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),
          fancybox=True, shadow=True)
plt.show()

这样列1会用红色绘制,列2用蓝色,列3用绿色,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:40:13