如何使用Seaborn为datetime64[ns]与类别变量绘制带边缘分布的hexbin图
解决方案
错误原因
jointplot的kind='hex'要求x、y轴均为连续型变量(数值/时间类型),直接传入分类类型的违规类型列作为x轴,不符合参数要求会触发报错。- 你提供的复现代码还存在两个额外问题:未将字符串格式的时间列转换为datetime类型、未指定
kind='hex'反而传入了和hexbin不兼容的hue参数。
实现步骤
- 先完成数据预处理:将时间列转换为
datetime64[ns]类型,将违规类型列转换为category类型,同时生成分类对应的数值编码用于绘图。 - 绘图时x轴传入数值编码,绘图完成后再将x轴刻度替换为分类标签即可保留分类含义。
- 边缘分布会自动匹配x、y轴的分布规律,无需额外调整。
可运行代码
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # 构造示例数据,可替换为你自己的数据集 ndf = pd.DataFrame({ 'date-time': ['2021-11-15 00:10:00','2021-11-15 00:20:00', '2021-11-15 00:15:00', '2021-11-15 00:30:00', '2021-11-15 00:25:00'], 'incident': ['a','b', 'a', 'c', 'b'] }) # 转换时间列格式 ndf['date-time'] = pd.to_datetime(ndf['date-time'], format="%Y-%m-%d %H:%M:%S") # 转换违规类型为分类变量并生成数值编码 ndf['incident'] = ndf['incident'].astype('category') ndf['incident_code'] = ndf['incident'].cat.codes sns.set_theme(style="ticks") # 绘制带边缘分布的hexbin图 g = sns.jointplot(data=ndf, x='incident_code', y='date-time', kind="hex", color="#4CB391") # 替换x轴刻度为分类标签,还原分类含义 g.ax_joint.set_xticks(range(len(ndf['incident'].cat.categories))) g.ax_joint.set_xticklabels(ndf['incident'].cat.categories) # 修改轴标签为业务含义 g.set_axis_labels(xlabel='违规类型', ylabel='发生时间') plt.tight_layout() plt.show()
补充说明
如果需要区分不同违规类型的颜色,可以放弃hexbin类型,改用kind='scatter'配合hue参数,同样可以保留边缘分布效果,更适配分类变量的可视化需求。
内容的提问来源于stack exchange,提问作者Valentin
相关产品推荐
相关产品推荐

