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

如何基于数值正负零实现时间序列散点图的颜色编码?

解决方案

错误原因

你写的列表推导式 for s in df1 实际遍历的是DataFrame的列名(字符串类型,比如'A'、'B'),不是单元格里的数值,所以和整数0比较时会抛出TypeError: '>' not supported between instances of 'str' and 'int'。

实现步骤

要实现按数值正负零标记不同颜色的散点图,需要逐个处理每一列的数据,为每个数据点分配对应颜色,再手动绘制散点:

完整代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

# 初始化DataFrame
df1 = pd.DataFrame({'A': [-1, 3, 9, 5, 0, -1, -1],
                  'B': [4, -5, 5, 7, 9, 8, 6],
                  'C': [7, 5, -3,-1, 5, 9, 3],
                  'D': [-3, 6, 7, 4, 0, -2, -1],
                 'date':['01-02-2020', '01-06-2020', '01-03-2021', '01-05-2021', '01-10-2021', '01-03-2022', '01-08-2022']})

# 转换日期格式并设为索引
df1['date'] = pd.to_datetime(df1['date'])
df1.set_index('date', inplace=True)

# 创建画布和轴
fig, ax = plt.subplots(figsize=(10, 6))

# 定义颜色映射规则
def get_color(val):
    if val > 0:
        return 'green'
    elif val < 0:
        return 'red'
    else:
        return 'yellow'

# 遍历每一列绘制散点
for col in df1.columns:
    # 为当前列的每个值生成对应颜色
    colors = df1[col].apply(get_color)
    # 绘制散点,x轴是日期索引,y轴是列值,指定颜色和标签
    ax.scatter(df1.index, df1[col], color=colors, marker='o', label=col)

# 设置X轴显示年月格式
date_form = DateFormatter("%Y-%m")
ax.xaxis.set_major_formatter(date_form)
# 旋转X轴标签,避免重叠
ax.figure.autofmt_xdate(rotation=45, ha='center')

# 添加图例和标题
ax.legend(loc='best')
ax.set_title('Scatter Plot with Color-coded Values')
ax.set_ylabel('Value')

plt.tight_layout()
plt.show()

代码说明

  • 颜色映射函数:get_color 根据数值正负零返回对应颜色,用apply方法为列中每个元素生成颜色列表。
  • 逐列绘制散点:循环DataFrame的每一列,用ax.scatter手动绘制,确保每个数据点都使用正确的颜色。
  • X轴格式设置:使用DateFormatter将X轴日期格式化为YYYY-MM的年月形式,解决日期显示问题。
  • 布局优化:tight_layout自动调整布局,避免标签重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:07:39