PySide中Matplotlib绘制雷达图报Figure无polar属性错误
报错根因
AttributeError: 'Figure' object has no property 'polar'由plt.subplots()参数传递错误导致:
- 你写的
plt.subplots(111, polar=True, dpi=100)中,位置参数111是老式的3位子图编号(代表1行1列布局下的第1个子图) - 这种简写传参模式下,
polar=True会被Matplotlib误判为Figure对象的初始化参数,而polar本身是极坐标子图Axes的专属配置属性,Figure类没有该属性就会抛出异常。
修复方案
1. 修正极坐标子图初始化代码
二选一即可,第一种写法适配所有Matplotlib 3.0+版本,可读性更好:
# 写法1(推荐):通过subplot_kw明确传递子图专属参数 fig1, self.ax = plt.subplots(nrows=1, ncols=1, subplot_kw={'polar': True}, dpi=100)
# 写法2:先创建画布再手动添加极坐标子图,兼容所有旧版本Matplotlib fig1 = plt.figure(dpi=100) self.ax = fig1.add_subplot(111, polar=True)
替换掉原来报错的fig1, self.ax = plt.subplots(111, polar=True, dpi=100)行即可解决当前属性报错。
2. 修复PySide嵌入场景下的绘图逻辑隐患
你现有代码里用plt.xticks()、plt.draw()这类pyplot全局接口操作嵌入Qt控件的画布,很容易出现多画布冲突、绘制不刷新、内容叠加的问题,同时缺少每次重绘前清空旧图层的逻辑,建议同步修改set_chart方法:
def set_chart(self, players, opts): angles = [n / float(len(opts)) * 2 * pi for n in range(len(opts))] angles += angles[:1] # 每次重绘前清空旧内容,避免图层叠加错乱 self.ax.clear() if self._data is not None: column_index_name = self._data.columns[0] tmp_df = self._data[self._data[column_index_name].isin(players)] tmp_df = tmp_df.loc[:, opts] tmp_df = tmp_df.set_index(column_index_name) # 提取两名选手的指标数据 values1 = tmp_df.iloc[0].tolist() values1 += values1[:1] values2 = tmp_df.iloc[1].tolist() values2 += values2[:1] # 用子图实例方法替换全局pyplot接口,避免跨画布冲突 self.ax.set_xticks(angles[:-1]) self.ax.set_xticklabels(opts) # 绘制第一名选手的雷达图区域 self.ax.plot(angles, values1) self.ax.fill(angles, values1, 'teal', alpha=0.1) # 绘制第二名选手的雷达图区域 self.ax.plot(angles, values2) self.ax.fill(angles, values2, 'red', alpha=0.1) # 触发当前画布重绘刷新 self.draw()
内容的提问来源于stack exchange,提问作者soy_elparce
相关产品推荐
相关产品推荐

