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

如何为Matplotlib雷达图添加无失真半透明宝可梦类型图标背景?

宝可梦雷达图添加图标失真问题解决

我正在做实验室课程的数据分析项目,分析宝可梦数据集,目前进度顺利。已经用雷达图展示各类型宝可梦的平均属性分布,冰系的雷达图能正常生成。但尝试给雷达图添加对应类型图标优化视觉效果时,图标出现严重失真。我希望把图标放在雷达图圆周内部,还要带点透明度,当前代码如下:

import numpy as np
import matplotlib.pyplot as plt

statsLabel = ['HP', 'Attack', 'Defense', 'Sp. Attack', 'Sp. Defense', 'Speed']
stats = [77, 83, 77, 74, 77, 66]
angles = np.linspace(0, 2*np.pi, len(statsLabel), endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
ax.set_ylim(0, 110)
ax.set_yticklabels([])
stats = np.concatenate((stats, [stats[0]]))  
ax.plot(angles, stats ,linewidth=1, linestyle='solid', label="First Set")  
ax.fill(angles, stats, alpha=0.1)
ax.set_thetagrids(angles[:-1] * 180/np.pi, statsLabel)
for angle, value in zip(angles, stats):
        ax.text(angle, value+10, str(value))
plt.title('Stats do tipo Ice')
file = "Ice_icon_SwSh.png"
img = plt.imread(file)
plt.imshow(img)
plt.show()

问题原因与解决方法

原代码用plt.imshow()直接绘图,会在全局笛卡尔坐标系中渲染图标,和极坐标子图的坐标系不匹配,导致位置错误和比例失真。以下是修正后的代码:

import numpy as np
import matplotlib.pyplot as plt

statsLabel = ['HP', 'Attack', 'Defense', 'Sp. Attack', 'Sp. Defense', 'Speed']
stats = [77, 83, 77, 74, 77, 66]
angles = np.linspace(0, 2*np.pi, len(statsLabel), endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
ax.set_ylim(0, 110)
ax.set_yticklabels([])
stats = np.concatenate((stats, [stats[0]]))  
ax.plot(angles, stats ,linewidth=1, linestyle='solid', label="First Set")  
ax.fill(angles, stats, alpha=0.1)
ax.set_thetagrids(angles[:-1] * 180/np.pi, statsLabel)
for angle, value in zip(angles, stats):
        ax.text(angle, value+10, str(value))
plt.title('Stats do tipo Ice')

# 图标加载与渲染修正
file = "Ice_icon_SwSh.png"
img = plt.imread(file)
# 设置图标显示范围:以极坐标中心(0,0)为原点,半径40的区域
icon_radius = 40
extent = [-icon_radius, icon_radius, -icon_radius, icon_radius]
# 在极坐标子图中渲染图标,保持比例+设置透明度
ax.imshow(img, extent=extent, alpha=0.5, aspect='equal')

plt.show()

关键修改说明

  • 改用ax.imshow()将图标绑定到极坐标子图,确保坐标系一致
  • 通过extent参数定义图标在极坐标中的显示范围,让它居中于雷达图内部
  • 添加alpha=0.5设置透明度,避免遮挡雷达图的属性线条和数值
  • 用aspect='equal'强制保持图标的原始比例,防止拉伸失真

内容的提问来源于stack exchange,提问作者Gustavo Lima

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:32:55