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

使用Pandas plot标注时出现StrCategoryConverter错误的原因与解决方法

Pandas plot结合annotate报错的原因与解决方法

当使用Pandas的df.plot()绘制折线图并调用annotate()添加标注时,抛出错误:

ValueError: Missing category information for StrCategoryConverter; this might be caused by unintendedly mixing categorical and numeric data

但使用Matplotlib原生方法实现相同逻辑却能正常运行。给定的DataFrame数据如下:

data = {'Unit': {0: 'Admin ', 1: 'C-Level', 2: 'Engineering', 3: 'IT', 4: 'Manufacturing', 5: 'Sales'}, 'Mean': {0: 4.642857142857143, 1: 4.83, 2: 4.048, 3: 4.237317073170732, 4: 4.184319526627219, 5: 3.9904545454545453}}
result=pd.DataFrame(data)

错误原因

Pandas的plot()方法默认会将字符串类型的x轴列(这里的Unit列)转换为分类数据类型(Categorical),此时x轴的底层是用数值索引(0、1、2...)来映射分类标签的。而当你直接使用原始字符串标签(如row['Unit'])作为annotate()的x参数时,Matplotlib无法匹配到分类轴对应的数值索引,从而触发分类信息缺失的错误。

而Matplotlib原生方法是直接将字符串作为刻度文本,x轴本质是数值型的位置索引,因此不会有类型不兼容的问题。

解决方法

方法1:禁用Pandas的分类轴转换

在调用df.plot()时,添加categorical=False参数,强制Pandas不将x轴列转换为分类类型,这样x轴会和Matplotlib原生逻辑一致,直接使用字符串刻度,此时annotate()可以正常使用字符串标签定位:

import pandas as pd
import matplotlib.pyplot as plt

data = {'Unit': {0: 'Admin ', 1: 'C-Level', 2: 'Engineering', 3: 'IT', 4: 'Manufacturing', 5: 'Sales'}, 'Mean': {0: 4.642857142857143, 1: 4.83, 2: 4.048, 3: 4.237317073170732, 4: 4.184319526627219, 5: 3.9904545454545453}}
result=pd.DataFrame(data)

# 绘制折线图,禁用分类转换
ax = result.plot(x='Unit', y='Mean', kind='line', categorical=False, marker='o')

# 添加标注
for idx, row in result.iterrows():
    ax.annotate(f'{row["Mean"]:.2f}', (row['Unit'], row['Mean']), textcoords="offset points", xytext=(0,10), ha='center')

plt.tight_layout()
plt.show()

方法2:使用分类轴的数值索引定位

如果需要保留Pandas的分类轴特性,可以通过DataFrame的索引作为x轴的数值位置来进行标注,此时annotate()的x参数传入行索引(0到5),而不是字符串标签:

import pandas as pd
import matplotlib.pyplot as plt

data = {'Unit': {0: 'Admin ', 1: 'C-Level', 2: 'Engineering', 3: 'IT', 4: 'Manufacturing', 5: 'Sales'}, 'Mean': {0: 4.642857142857143, 1: 4.83, 2: 4.048, 3: 4.237317073170732, 4: 4.184319526627219, 5: 3.9904545454545453}}
result=pd.DataFrame(data)

# 绘制折线图,默认使用分类轴
ax = result.plot(x='Unit', y='Mean', kind='line', marker='o')

# 添加标注,使用行索引作为x位置
for idx, row in result.iterrows():
    ax.annotate(f'{row["Mean"]:.2f}', (idx, row['Mean']), textcoords="offset points", xytext=(0,10), ha='center')

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:27:09