我有一本我想要绘制的字典。我试图在x值处绘制一条垂直线,其中50%的y值位于上方,50%位于下方。
我尝试通过查找dict.values(y值)的中位数来获取匹配键。但是我得到一个太低的x值,这肯定不是中等x值。有谁知道我怎么能做到这一点?这是我到目前为止所得到的:
hist1, hist2 = np.genfromtxt('./Unfold_Accessibility/social_shortest_path_durations_histogram.txt', unpack=True)
hist = np.genfromtxt('./Unfold_Accessibility/social_shortest_path_durations_histogram.txt')
dl1 = dict(hist)
median1 = dl1.keys()[dl1.values().index(np.median(dl1.values()))]
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(hist1, hist2, '-', color='blue', label='data')
ax.axvline(median1, color='blue', linestyle='--', label='mean p=1')
plt.title('Shortest Path Duration Cumulative')
plt.legend(bbox_to_anchor=(1.6, 1))
plt.xlabel('Time')
plt.ylabel('Probability')
plt.grid(True)
plt.show()
yaverage1= np.sum(dl1.values())/2
untilhalf1 = 0
for key in dl1.iterkeys():
if untilhalf1 < yaverage1:
value = dl1[key]
untilhalf1= untilhalf1 + value
else:
median1=[k for (k, v) in dl1.iteritems() if k == key]
print 'median1:', median1
break
答案 0 :(得分:0)
您需要在迭代之前对键进行排序:
例如:
def Quantile(self, distribution, quantile):
target = np.sum(distribution.values()) * quantile
currentsum = 0.0
for key in sorted(distribution.keys()):
if currentsum < target:
currentsum = currentsum + distribution[key]
if currentsum >= target:
return key