Matplotlib子图无法输出及掩码元素转NaN警告问题求助
问题分析与解决方案
首先明确两个现象的本质:
<matplotlib.collections.PathCollection at ...>不是错误,只是plt.scatter()函数返回的对象在交互式环境(比如Jupyter)中被自动打印出来,完全不影响绘图结果,无需处理。- “converting a masked element to nan”警告由两个核心问题导致:
- 你覆盖了颜色字典变量,后续颜色映射逻辑完全错误
- 数据可能存在缺失值,或部分
Region值不在颜色映射字典中
具体修复步骤
- 避免覆盖颜色字典:将原颜色字典的变量名改为
color_map,防止被映射后的颜色序列覆盖 - 针对数据集单独映射颜色:用原颜色字典分别处理对应年份的
Region列,保证颜色序列长度与数据匹配 - 可选:清理缺失值:过滤掉含缺失值的行,彻底消除警告
修改后的代码
# 拆分年份数据 year2000 = imported_dataframe[imported_dataframe['Year'] == 2000] year2005 = imported_dataframe[imported_dataframe['Year'] == 2005] year2010 = imported_dataframe[imported_dataframe['Year'] == 2010] year2015 = imported_dataframe[imported_dataframe['Year'] == 2015] # 创建子图 fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) # 定义颜色映射字典,避免被覆盖 color_map = { 'Africa': 'orchid', 'Americas': 'darkcyan', 'Asia': 'blue', 'Europe': 'yellow', 'Oceania': 'purple' } # 处理全量数据的颜色和坐标 x, y = imported_dataframe['Proportion of births attended by skilled health personnel (%)'], imported_dataframe['Maternal mortality ratio'] colors_full = imported_dataframe.Region.map(color_map) # 过滤缺失值,消除警告 mask_full = x.notna() & y.notna() & colors_full.notna() ax1.scatter(x[mask_full], y[mask_full], c=colors_full[mask_full]) ax1.set_title('All Years') # 处理2000年数据的颜色和坐标 x1, y1 = year2000['Proportion of births attended by skilled health personnel (%)'], year2000['Maternal mortality ratio'] colors_2000 = year2000.Region.map(color_map) # 过滤缺失值 mask_2000 = x1.notna() & y1.notna() & colors_2000.notna() ax2.scatter(x1[mask_2000], y1[mask_2000], c=colors_2000[mask_2000]) ax2.set_title('Year 2000') # 添加轴标签提升可读性 fig.supxlabel('Proportion of births attended by skilled health personnel (%)') fig.supylabel('Maternal mortality ratio') plt.show()
关键说明
- 核心错误修正:你之前用
colors = imported_dataframe.Region.map(colors)把原颜色字典替换成了Series,后续year2000.Region.map(colors)相当于用一个Series去做映射,逻辑完全错误,改名后彻底解决这个问题。 - 缺失值过滤:通过掩码过滤掉含NaN的行,既消除了警告,也保证了绘图数据的有效性。
- 添加
plt.show():在脚本运行环境中确保图表正常显示,同时避免打印PathCollection对象。
内容的提问来源于stack exchange,提问作者user341191
相关产品推荐
相关产品推荐

