Python 从def()内部获取值
我定义了一个函数来绘制直方图。在这个函数中,我正在对我在图上点击2次获得的数据进行一些分析 我的代码如下:Python 从def()内部获取值,python,histogram,user-defined-functions,Python,Histogram,User Defined Functions,我定义了一个函数来绘制直方图。在这个函数中,我正在对我在图上点击2次获得的数据进行一些分析 我的代码如下: def hist_maker(): heights,edges = np.histogram(data, 1000) edges = edges[:-1]+(edges[1]-edges[0]) fig, ax = plt.subplots() ax.plot(edges,heights)
def hist_maker():
heights,edges = np.histogram(data, 1000)
edges = edges[:-1]+(edges[1]-edges[0])
fig, ax = plt.subplots()
ax.plot(edges,heights) # plot histogram
plt.yscale('log', nonposy='clip')
ax.set(title=titl, xlabel='ADC Value(DN/40)', ylabel='Frequency')
point1, point2 = fig.ginput(2) # get input from 2 clicks on figure
ax.axvspan(point1[0], point2[0], color='red', alpha=0.5) # paint selected area in red
mask = (edges>point1[0]) & (edges<point2[0])
# calculate which values are selected and display mean
fig.text(0.2,0.84,'Mean: ' + str((sum(edges[mask]*heights[mask])/sum(heights[mask]))))
mean = sum(edges[mask]*heights[mask])/sum(heights[mask])
mean_noise = edges[heights.argmax() # Find the x value corresponding to the max y value
fig.text(0.2,0.8,'Std: ' + str(g))
def hist_maker():
高度,边缘=np.直方图(数据,1000)
边=边[:-1]+(边[1]-边[0])
图,ax=plt.子批次()
ax.绘图(边缘、高度)#绘图柱状图
plt.yscale('log',nonposy='clip')
ax.set(title=titl,xlabel='ADC值(DN/40'),ylabel='Frequency')
点1,点2=图ginput(2)#通过在图上单击两次获取输入
ax.axvspan(点1[0],点2[0],color='red',alpha=0.5)#将选定区域涂成红色
掩码=(边>点1[0])&(边最简单的解决方案-函数的第一行应该是:
global mean_noise
如果随后运行(在函数外部):
打印应该可以。如果你颠倒这两行的顺序,你会得到一个名称错误
不过,请注意,这通常被认为是不好的编程。通常认为更好的解决方案是在函数末尾返回mean_noise
。返回mean_noise或将其作为全局变量(声明在函数范围之外)使用全局均值噪声有效,并且允许我以后在代码中使用它。但是,返回均值噪声不起作用。让我检查一下我是否正确使用了它。对于我的问题中的代码,我所做的就是在末尾添加返回均值噪声,并且每当我使用该函数时,它都应该打印值?如果这是正确的,那么a)当我尝试时,它不会打印值,b)它只会打印一个数字,不允许我以后使用它,因为您将添加返回mean
,然后在使用该函数的代码中,您将编写mean\u noise=hist\u maker()
hist_maker()
print(mean_noise)