我的问题通常是:我有一个函数,可以创建并保存直方图。在我的代码中,我两次运行该函数:第一次使用一个数据数组创建和保存一个绘图,第二次使用另一个数据数组创建和保存第二个绘图。程序完成后,我得到2个.png文件:第一个包含一个数据数组的直方图,第二个包含第一个和第二个数据数组的直方图!我需要的是一个数组的一个图,而另一个数组的另一个图。我的主意会打击,我无法理解,这是怎么回事。有人可以给我一个提示吗?
这是我的代码和生成的图像的一部分:
def mode(station_name, *args):
...
#before here the 'temp' data array is generated
temp_counts = {}
for t in temp:
if t not in temp_counts:
temp_counts[t] = 1
else:
temp_counts[t] += 1
print(temp_counts) **#this dictionary has DIFFERENT content being printed in two function runs**
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))
#---------------------------------------------------------------------------------------------------
mode(station_name, [...])
mode(station_name, [...])
如果使用plt.plotsomething..
该图,则会将其添加到当前使用的图形中,因此第二个直方图将添加到第一个直方图中。我建议使用matplotlib对象API以避免混淆:创建图形和轴,然后从它们开始生成图。这是您的代码:
def mode(station_name, *args):
...
#before here the 'temp' data array is generated
temp_counts = {}
for t in temp:
if t not in temp_counts:
temp_counts[t] = 1
else:
temp_counts[t] += 1
print(temp_counts) **#this dictionary has DIFFERENT content being printed in two function runs**
x = []
for k, v in temp_counts.items():
x += [k for _ in range(v)]
fig, ax = plt.subplots(1):
ax.hist(x, bins="auto")
ax.grid(True)
fig.savefig('{}.png'.format(station_name))
#---------------------------------------------------------------------------------------------------
mode(station_name, [...])
mode(station_name, [...])
这应该为您完成工作
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句