在Python中使用Matplotlib或Pandas绘制直方图

3j86kqsm  于 2023-10-24  发布在  Python
关注(0)|答案(1)|浏览(146)

我已经从这个论坛上的不同职位,但我找不到一个答案,我看到的行为。
我有一个CSV文件,它的头有许多条目,每个条目有300个点。(csv文件的列)我想绘制一个直方图。x轴包含该列上的元素,y轴应该有每个bin内的样本数量。由于我有300个点,所有bin中的样本总数加在一起应该是300,所以y轴应该从0到50(只是一个例子)。然而,这些值是巨大的(400 e8),这是没有意义的。

表点mydata示例

1 |250.23 e-9 2| 250.123e-9.|三百|251.34e-9

请检查我的代码,下面。我使用pandas打开csv和Matplotlib的休息。

  1. df=pd.read_csv("/home/pcardoso/raw_data/myData.csv")
  2. # Figure parameters
  3. figPath='/home/pcardoso/scripts/python/matplotlib/figures/'
  4. figPrefix='hist_' # Prefix to the name of the file.
  5. figSuffix='_something' # Suffix to the name of the file.
  6. figString='' # Full string passed as the figure name to be saved
  7. precision=3
  8. num_bins = 50
  9. columns=list(df)
  10. for fieldName in columns:
  11. vectorData=df[fieldName]
  12. # statistical data
  13. mu = np.mean(vectorData) # mean of distribution
  14. sigma = np.std(vectorData) # standard deviation of distribution
  15. # Create plot instance
  16. fig, ax = plt.subplots()
  17. # Histogram
  18. n, bins, patches = ax.hist(vectorData, num_bins, density='True',alpha=0.75,rwidth=0.9, label=fieldName)
  19. ax.legend()
  20. # Best-fit curve
  21. y=mlab.normpdf(bins, mu, sigma)
  22. ax.plot(bins, y, '--')
  23. # Setting axis names, grid and title
  24. ax.set_xlabel(fieldName)
  25. ax.set_ylabel('Number of points')
  26. ax.set_title(fieldName + ': $\mu=$' + eng_notation(mu,precision) + ', $\sigma=$' + eng_notation(sigma,precision))
  27. ax.grid(True, alpha=0.2)
  28. fig.tight_layout() # Tweak spacing to prevent clipping of ylabel
  29. # Saving figure
  30. figString=figPrefix + fieldName +figSuffix
  31. fig.savefig(figPath + figString)
  32. plt.show()
  33. plt.close(fig)

总而言之,我想知道如何使y轴值正确。
编辑:2020年7月6日

我希望密度估计器遵循这样的图:

egdjgwm8

egdjgwm81#

不要使用density='True',因为使用该选项时,显示的值是bin中的成员除以bin的宽度。如果该宽度很小(如在相当小的x-值的情况下,值会变大)。

**编辑:**好的,要对赋范曲线进行非赋范,需要将其乘以点数和一个bin的宽度。我做了一个更精简的例子:

  1. from numpy.random import normal
  2. from scipy.stats import norm
  3. import pylab
  4. N = 300
  5. sigma = 10.0
  6. B = 30
  7. def main():
  8. x = normal(0, sigma, N)
  9. h, bins, _ = pylab.hist(x, bins=B, rwidth=0.8)
  10. bin_width = bins[1] - bins[0]
  11. h_n = norm.pdf(bins[:-1], 0, sigma) * N * bin_width
  12. pylab.plot(bins[:-1], h_n)
  13. if __name__ == "__main__":
  14. main()
展开查看全部

相关问题