如何修复ConversionError: Failed to convert value(s) to axis units: 'Toyota'错误?
解决Seaborn绘图中的ConversionError: Failed to convert value(s) to axis units错误
问题根源
你的plt.text()调用中,y坐标参数传入了字符串类型的'Make'列值(比如'Toyota'),但y轴对应的是数值型的Units Sold数据,Matplotlib无法将字符串转换为轴的数值单位,因此触发该错误。
修复代码
将plt.text()的y坐标替换为对应行的Units Sold数值(可添加偏移量优化文本位置):
fig = plt.figure(figsize=(16,8)) sns.barplot(x=ncs_2007_2017.index, y='Units Sold', data=ncs_2007_2017) for i in range(len(ncs_2007_2017.index)): # 用Units Sold的数值作为y坐标,添加偏移让文本显示在柱子上方 plt.text(i, ncs_2007_2017['Units Sold'].iloc[i] + 500, ncs_2007_2017['Make'].iloc[i], ha='center', va='bottom') plt.show()
可选调整
- 若要将文本放在柱子内部,可把y坐标改为
ncs_2007_2017['Units Sold'].iloc[i]/2,并设置va='center'。 - 偏移量(示例中的500)可根据你的数据量级调整,避免文本与柱子重叠。
内容的提问来源于stack exchange,提问作者Jj Encrypt
相关产品推荐
相关产品推荐

