【问题标题】:Align histogram bars - Python对齐直方图条 - Python
【发布时间】:2018-01-21 23:19:52
【问题描述】:

我需要使直方图的条居中。

x = array
y = [0,1,2,3,4,5,6,7,8,9,10]

num_bins = len(array)
n, bins, patches = plt.hist(x, num_bins, facecolor='green', alpha=0.5)
barWidth=20
x.bar(x, y, width=barWidth, align='center')

plt.show()

我需要的是,它看起来像 this picture 中的那个

我几乎尝试了所有方法,但仍然无法通过。 谢谢大家

【问题讨论】:

    标签: python alignment histogram


    【解决方案1】:

    对于您的任务,我认为最好使用 NumPy 计算直方图并使用 bat 函数进行绘图。请参考以下代码,了解如何使用 bin_edges。

    import matplotlib.pyplot as plt
    import numpy as np
    
    num_samples = 100
    num_bins = 10
    lb, ub = 0, 10 # lower bound, upper bound
    
    # create samples
    y = np.random.random(num_samples) * ub
    
    # caluculate histogram
    hist, bin_edges = np.histogram(y, num_bins, range=(lb, ub))
    width = (bin_edges[1] - bin_edges[0])
    
    # plot histogram
    plt.bar(bin_edges[:-1], hist, align='center', 
            width=width, edgecolor='k', facecolor='green', alpha=0.5)
    plt.xticks(range(num_bins))
    plt.xlim([lb-width/2, ub-width/2])
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多