X轴为分类数据的折线图绘制报错求助:'str' object has no attribute 'view'
折线图绘制报错:
'str' object has no attribute 'view' 解决方法 问题背景
尝试绘制Y轴为数值、X轴为分类(never、former、current)的折线图时,运行代码触发报错:'str' object has no attribute 'view',相关代码及数据集前10行如下:
原始代码
fig, axes = plt.subplots(nrows=2) fig.tight_layout(pad=3.2) newdata = newdf.groupby('smoking-number').mean().reset_index() sem = newdf.groupby('smoking-number').sem().reset_index() newdata['smoking-number'] = newdata['smoking-number'].map({1: 'never', 2: 'former', 3: 'current'}) newdata.plot.line(x='smoking-number',y='distance', yerr= sem, ax=axes[0],legend=False) newdata.plot.line(x='smoking-number',y='duration', yerr= sem, ax=axes[1],legend=False) upperbounddistance = max(newdata[['distance']].values)+max(sem[['distance']].values) lowerbounddistance = min(newdata[['distance']].values)-min(sem[['distance']].values) upperboundduration = max(newdata[['duration']].values)+max(sem[['duration']].values) lowerboundduration = min(newdata[['duration']].values)-min(sem[['duration']].values) axes[0].set_ylim(lowerbounddistance,upperbounddistance) axes[0].set_xlim(0.5,3.5) axes[1].set_ylim(lowerboundduration,upperboundduration) axes[1].set_xlim(0.5,3.5) axes[0].set_ylabel("Wayfinding distance") axes[0].set_xlabel("Smoking frequency") axes[1].set_ylabel("Wayfinding duration") axes[1].set_xlabel("Smoking frequency")
数据集newdf前10行
distance 10 48.146090 13 98.877301 17 66.670310 19 95.764316 21 78.737108 22 48.404197 25 63.910073 27 40.862231 28 50.223985 30 38.724922 duration 10 40.976006 13 90.093298 17 88.349603 19 82.737323 21 72.579054 22 40.059987 25 57.629693 27 38.419589 28 40.834470 30 34.813547 smoking-number 10 1.0 13 1.0 17 1.0 19 1.0 21 1.0 22 1.0 25 3.0 27 1.0 28 1.0 30 1.0
报错原因
- 折线图X轴不支持直接用字符串分类:将
smoking-number映射为字符串后,plot.line()无法将字符串作为连续坐标处理,底层调用view方法时触发类型错误。 yerr参数使用错误:传入整个semDataFrame,而非对应列的误差值,导致维度不匹配。- 坐标轴范围设置矛盾:
set_xlim(0.5,3.5)是针对数值型X轴的配置,与字符串分类轴不兼容。
修正后的代码
import matplotlib.pyplot as plt import pandas as pd fig, axes = plt.subplots(nrows=2, figsize=(8, 10)) fig.tight_layout(pad=3.2) # 分组计算均值和标准误 newdata = newdf.groupby('smoking-number').mean().reset_index() sem = newdf.groupby('smoking-number').sem().reset_index() # 单独生成分类标签,保留数值型smoking-number用于绘图 category_labels = {1: 'never', 2: 'former', 3: 'current'} newdata['category'] = newdata['smoking-number'].map(category_labels) # 绘制折线图,指定对应列的误差值 newdata.plot.line(x='smoking-number', y='distance', yerr=sem['distance'], ax=axes[0], legend=False, marker='o') newdata.plot.line(x='smoking-number', y='duration', yerr=sem['duration'], ax=axes[1], legend=False, marker='o') # 计算并设置Y轴范围 upperbounddistance = newdata['distance'].max() + sem['distance'].max() lowerbounddistance = newdata['distance'].min() - sem['distance'].min() upperboundduration = newdata['duration'].max() + sem['duration'].max() lowerboundduration = newdata['duration'].min() - sem['duration'].min() axes[0].set_ylim(lowerbounddistance, upperbounddistance) axes[1].set_ylim(lowerboundduration, upperboundduration) # 替换X轴刻度为分类名称 axes[0].set_xticks(newdata['smoking-number']) axes[0].set_xticklabels(newdata['category']) axes[1].set_xticks(newdata['smoking-number']) axes[1].set_xticklabels(newdata['category']) # 设置坐标轴中文标签 axes[0].set_ylabel("寻路距离") axes[0].set_xlabel("吸烟频率") axes[1].set_ylabel("寻路时长") axes[1].set_xlabel("吸烟频率") plt.show()
关键修正说明
- 保留数值型X轴:不直接修改
smoking-number的数值类型,而是单独生成分类标签列,用数值字段绘图后替换刻度标签,避免字符串轴的兼容性问题。 - 修正误差参数:传入对应列的误差值(如
sem['distance']),确保与Y轴数据维度匹配。 - 优化范围计算:直接使用DataFrame的
max()/min()方法,简化数组取值操作。 - 自定义刻度标签:通过
set_xticks和set_xticklabels将数值刻度替换为分类名称,实现需求的分类X轴显示。
内容的提问来源于stack exchange,提问作者Caledonian26
相关产品推荐
相关产品推荐

