这并不完全是在 MS Excel 中创建加权直方图的解决方案,而是实现相同结果的替代方法。使用 python 的 numpy 库来实现这一点更容易(编码效率不高,但希望有人可以改进它?):
import numpy as np
from matplotlib import pyplot as plt
#Setting up empty lists
minZ = []
minZ_Weight = []
maxZ = []
maxZ_Weight = []
#Choosing bin values
Bins = np.array([-1.3,-1.2,-1.1,-1.0,-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0])
if __name__ == '__main__':
data = open("Height_data.csv")
data.readline()
#read a text file line by line
for line in data:
item = line.split(",")#Items in a csv file are split according to ','
#convert text file strings to floats and add to relevant list
minZ += [float(item[6])]
minZ_Weight += [float(item[2])]
maxZ += [float(item[8])]
maxZ_Weight += [float(item[2])]
#Creating numpy array (keeps the same order as the values were put in)
minH_Array = np.array(minH)
minH_W_Array = np.array(minH_W)
maxH_Array = np.array(maxH)
maxH_W_Array = np.array(maxH_W)
hist, bin_edges = np.histogram(a=minH_Array, bins = Bins, weights = minH_W_Array)
hist2,bin_edges2 = np.histogram(a=maxH_Array, bins=Bins, weights=maxH_W_Array)
#Plotting Min and Max Z values separately
fig = plt.figure(figsize = plt.figaspect(0.45))
ax = fig.add_subplot(1,2,1)
plt.title("Minimum Heights")
ax.bar(bin_edges[:-1],hist,width=0.1)
ax.set_xlim(min(bin_edges),max(bin_edges))
ax.set_ylim([0,100000])
ax = fig.add_subplot(1,2,2)
plt.title("Maximum Heights")
ax.bar(bin_edges2[:-1],hist2,width=0.1)
ax.set_xlim(min(bin_edges2),max(bin_edges2))
ax.set_ylim([0,100000])
#Appends new values to the end of the numpy array
combined_H = np.append(arr=minH_Array,values=maxH_Array)
combined_W = np.append(arr=minH_W_Array, values=maxH_W_Array)
histC, bin_edgesC = np.histogram(a=combined_H, bins = Bins, weights = combined_W)
#OR you can plot them on the same axis
#Plotting Min and Max on same axis
plt.title("Combined Histogram of Heights")
plt.bar(bin_edgesC[:-1],histC,width=0.1)
plt.xlim(min(bin_edges),max(bin_edges))
plt.show()
对于那些感兴趣的人来说,Matlab 是我能找到的唯一其他创建加权直方图的方法:Matlab Weighted Histogram(但我完全没有使用它的经验,因此选择了 Python)。