Matplotlib绘制直方图异常:两次绘图结果叠加问题求助
问题原因与解决方法
这个问题其实是Matplotlib的状态机绘图机制导致的——默认情况下,Matplotlib会在同一个画布(Figure)和坐标轴(Axes)上持续添加新的绘图内容,不会自动重置。你第二次调用mode函数时,并没有创建新的绘图区域,所以第二次的直方图会直接叠加在第一次的图上,最终第二张图就包含了两次的数据。
具体的修复方案
你可以通过以下几种方式解决,选一种适合你的即可:
方案1:每次绘图前创建新画布
在调用plt.hist()之前,添加plt.figure()来创建一个全新的画布,这样每次绘图都是独立的:
def mode(station_name, *args): ... # 此处生成'temp'数据数组 temp_counts = {} for t in temp: if t not in temp_counts: temp_counts[t] = 1 else: temp_counts[t] += 1 print(temp_counts) x = [] for k, v in temp_counts.items(): x += [k for _ in range(v)] plt.figure() # 新增:创建新画布 plt.hist(x, bins="auto") plt.grid(True) plt.savefig('{}.png'.format(station_name))
方案2:绘图完成后清除当前画布
在savefig()之后,调用plt.clf()(清除当前画布内容)或者plt.close()(关闭当前画布),这样下次绘图时就是空白的:
def mode(station_name, *args): ... # 此处生成'temp'数据数组 temp_counts = {} for t in temp: if t not in temp_counts: temp_counts[t] = 1 else: temp_counts[t] += 1 print(temp_counts) x = [] for k, v in temp_counts.items(): x += [k for _ in range(v)] plt.hist(x, bins="auto") plt.grid(True) plt.savefig('{}.png'.format(station_name)) plt.clf() # 新增:清除当前画布内容
方案3:使用面向对象API(更推荐,避免状态混乱)
如果想更清晰地控制绘图对象,建议使用Matplotlib的面向对象模式,显式创建Figure和Axes:
def mode(station_name, *args): ... # 此处生成'temp'数据数组 temp_counts = {} for t in temp: if t not in temp_counts: temp_counts[t] = 1 else: temp_counts[t] += 1 print(temp_counts) x = [] for k, v in temp_counts.items(): x += [k for _ in range(v)] # 显式创建画布和轴 fig, ax = plt.subplots() ax.hist(x, bins="auto") ax.grid(True) fig.savefig('{}.png'.format(station_name)) plt.close(fig) # 关闭画布释放资源
为什么print的字典是对的?
你看到两次print(temp_counts)的内容不同,这说明你的数据处理逻辑是没问题的——问题完全出在Matplotlib的绘图状态没有重置,导致第二次绘图叠加在了第一次的画布上。
内容的提问来源于stack exchange,提问作者Outlaw
相关产品推荐
相关产品推荐

