Skip to main content
 首页 » 编程设计

python之字典到直方图

2024年11月01日10zlslch

我有一本字典叫

样本 = {5.207403005022627: 0.69973543384229719, 6.8970222167794759: 0.080782939731898179, 7.8338517407140973: 0.10308138382545,0.103081383825415 5505334:0.018640838362318335、10.418899728838058:0.14427355015329846、5.3983946820220501:0.51319796560976771

这里字典的 keys 表示 x 轴上的点,字典的 values 表示特定 x 的点的值 即 y=f(x)。

如何在 0-10 区间内使用 bin sizes=1 创建直方图

请您参考如下方法:

您可以使用 keys 作为 bin 位置,使用 values 作为直方图的权重,执行以下操作:

import numpy as np 
import matplotlib.pyplot as plt 
 
d = {5.207403005022627: 0.69973543384229719, 6.8970222167794759: 0.080782939731898179, 7.8338517407140973: 0.10308033284258854, 8.5301143255505334: 0.018640838362318335, 10.418899728838058: 0.14427355015329846, 5.3983946820220501: 0.51319796560976771} 
a = np.array(d.items()) 
a = a[np.argsort(a[:,0])] 
x, weights = a.T 
 
plt.figure(figsize=(5,4)) 
plt.hist(x, weights=weights) 
plt.show() 

给出: