[英]Python and plotting the histograms (using matplotlib)
My problem in general: I have a function, that creates and saves the histograms.我的一般问题是:我有一个函数,可以创建和保存直方图。 In my code I run the function twice: 1st time to create and save one plot with one data array, 2nd time to create and save second plot with another data array.在我的代码中,我运行了两次函数:第一次用一个数据数组创建和保存一个图,第二次用另一个数据数组创建和保存第二个图。 After the completion of the program, I get 2 .png files: the 1st one contains the histogram of one data array, the 2nd one contains histogram of the first AND the second data arrays!程序完成后,我得到 2 个 .png 文件:第一个包含一个数据数组的直方图,第二个包含第一个和第二个数据数组的直方图! What I need is one plot for one array, and second plot for another array.我需要的是一个数组的一个图,另一个数组的第二个图。 My mind's gonna blow, I just can't get, what's wrong here.我的脑子要炸了,我就是不明白,这是怎么了。 Might somebody give me a clue?有人可以给我一个线索吗?
Here's a part of my code and resulting images:这是我的代码和结果图像的一部分:
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, [...])
the 'like' of 1 image i get我得到的 1 张图像的“喜欢”
the 'like' of 2 image i get我得到的 2 个图像的“喜欢”
real images i get after my full script finishes #1我的完整脚本完成后得到的真实图像 #1
real images i get after my full script finishes #2我的完整脚本完成后得到的真实图像 #2
If you use plt.plotsomething..
the plot is added to the current figure in use, therefore the second histogram is added to the first.如果您使用plt.plotsomething..
该图将添加到当前使用的图形中,因此第二个直方图将添加到第一个中。 I suggest using the matplotlib object API to avoid confusion: you create figure and axis and you generate your plots starting from them.我建议使用 matplotlib 对象 API 来避免混淆:您创建图形和轴并从它们开始生成您的绘图。 Here's your code:这是你的代码:
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, [...])
This should do the job for you这应该适合你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.