宝可梦属性对比:解决Pandas平行坐标图多子图绘制异常问题
问题解决:平行坐标图多子图绘制异常
问题现象
使用Pandas的parallel_coordinates()结合Matplotlib子图功能时,所有图形都被绘制到最后一个子图中,前两个子图为空。
错误原因
pd.plotting.parallel_coordinates()默认会使用当前活跃的Matplotlib轴,若直接用ax1 = pd.plotting.xxx的方式赋值,会覆盖最初创建的子图轴对象,导致所有绘图操作都指向最后一次生成的轴。- 代码中存在数据引用错误:后两个子图重复使用了
df_fireWater,而非对应筛选出的df_waterPsychic和df_waterRock。
修正后的代码
import pandas as pd import matplotlib.pyplot as plt values = ['Attack', 'Defense', 'HP', 'Sp.Attack', 'Sp.Defense', 'Speed'] # 创建1行3列的子图,获取三个轴对象 fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15,5)) fig.tight_layout(pad=3) # 增加间距避免标签重叠 # 第一个子图:火属性 vs 水属性 df_fireWater = df_pokemon[(df_pokemon['Primary Type'] == 'FIRE') | (df_pokemon['Primary Type'] == 'WATER')] # 关键:通过ax参数指定绘制到ax1,不要重新赋值ax1 pd.plotting.parallel_coordinates(df_fireWater, 'Primary Type', values, color=('red', 'blue'), ax=ax1) ax1.set_title('FIRE vs WATER') # 第二个子图:水属性 vs 超能力属性 df_waterPsychic = df_pokemon[(df_pokemon['Primary Type'] == 'WATER') | (df_pokemon['Primary Type'] == 'PSYCHIC')] pd.plotting.parallel_coordinates(df_waterPsychic, 'Primary Type', values, color=('blue', 'violet'), ax=ax2) ax2.set_title('WATER vs PSYCHIC') # 第三个子图:水属性 vs 岩石属性 df_waterRock = df_pokemon[(df_pokemon['Primary Type'] == 'WATER') | (df_pokemon['Primary Type'] == 'ROCK')] pd.plotting.parallel_coordinates(df_waterRock, 'Primary Type', values, color=('blue', 'brown'), ax=ax3) ax3.set_title('WATER vs ROCK') plt.show()
核心修正点
- 调用
parallel_coordinates时,通过**ax参数**指定目标子图轴,禁止用赋值语句覆盖原轴对象。 - 修正DataFrame引用错误,确保每个子图使用对应筛选的数据。
- 为子图添加标题,便于区分不同属性对比组。
内容的提问来源于stack exchange,提问作者Vanna
相关产品推荐
相关产品推荐

