Python单图绘制多散点图异常:仅显示最后一个图求助
解决单图多类别散点图只显示最后一个类别的问题
嘿,我看到你的问题了——运行代码后只有最后一个类别的散点图显示,这是因为循环里犯了个变量名的小错误,而且代码缺少图例来区分不同类别。咱们来一步步修复,同时让代码能完美适配任意数量的类别(包括你现在的10个类别):
问题根源
原代码的循环里,你用了parent_categories[parent_category_name]来筛选类别,但parent_category_name是DataFrame的列名,不是循环变量!循环变量是parent_category_n,这就导致每次循环都无法正确筛选对应类别的数据,最后只有最后一次循环偶然生效,所以只显示了最后一个类别。
修正后的完整代码
import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np sample = [ ['For business', 0.7616104043587437], ['For home and cottages', 0.6890139579274699], ['Consumer electronics', 0.039868871866136635], ['Personal things', 0.7487893699793786], ['Services', 0.747226678171249], ['Services', 0.23463661173977313], ['Animals', 0.6504301798258314], ['For home and cottages', 0.49567857024037665], ['For home and cottages', 0.9852681814098107], ['Transportation', 0.8134867587477912], ['Animals', 0.49988690699674654], ['Consumer electronics', 0.15086800344617235], ['For business', 0.9485494576819328], ['Hobbies and Leisure', 0.25766871111905243], ['For home and cottages', 0.31704508627659533], ['Animals', 0.6192114570078333], ['Personal things', 0.5755788287287359], ['Hobbies and Leisure', 0.10106922056341394], ['Animals', 0.16834618003738577], ['Consumer electronics', 0.7570803588496894] ] train = pd.DataFrame(data=sample, columns=['parent_category_name','deal_probability']) parent_categories = train['parent_category_name'].unique() parent_categories_size = len(parent_categories) fig, ax = plt.subplots(figsize=(12,10)) colors = iter(cm.rainbow(np.linspace(0, 1, parent_categories_size))) # 直接遍历每个类别,避免索引错误 for category in parent_categories: # 筛选当前类别的数据 category_data = train[train['parent_category_name'] == category] # 绘制散点图,添加label用于图例 ax.scatter( range(len(category_data)), np.sort(category_data['deal_probability'].values), color=next(colors), label=category # 添加类别标签 ) plt.ylabel('likelihood that an ad actually sold something', fontsize=12) plt.title('Distribution of likelihood that an ad actually sold something', fontsize=14) # 添加图例,放在图外避免遮挡 plt.legend(title='Categories', bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() # 自动调整布局,适配图例 plt.show()
关键修改点
- 修复循环逻辑:把基于索引的循环改成直接遍历
parent_categories中的每个类别,彻底避免索引变量名混淆的问题,同时代码更易读。 - 添加类别标签与图例:每个散点图加上
label参数,最后调用plt.legend(),让你能清晰区分每个类别的数据分布。 - 优化布局:用
bbox_to_anchor把图例放在图的右侧,避免遮挡数据点,plt.tight_layout()自动调整整体布局。 - 动态适配类别数量:颜色生成和循环逻辑完全基于
parent_categories的长度,无论你后续数据集有多少类别,代码都能自动适配。
这样修改后,你就能在同一个Figure里看到所有10个类别的散点图,每个类别用不同颜色区分,还能通过图例清楚知道每个颜色对应的类别~
内容的提问来源于stack exchange,提问作者pablora
相关产品推荐
相关产品推荐

