【问题标题】:Python matplotlib histogram: edit x-axis based on maximum frequency in binPython matplotlib直方图:根据bin中的最大频率编辑x轴
【发布时间】:2016-04-26 09:27:54
【问题描述】:

我试图通过循环一系列包含值的数组来制作一系列直方图。对于每个数组,我的脚本都会生成一个单独的直方图。使用默认设置,这会产生直方图,其中频率最高的条形图触及图表顶部(this is what it looks like now)。我希望有一些空间:this is what I want it to look like.

我的问题是:如何使 y 轴的最大值取决于我的 bin 中出现的最大频率?我希望 y 轴比我最长的条稍长。

我不能通过这样设置值来做到这一点:

plt.axis([100, 350, 0, 5])  #[xmin, xmax, ymin, ymax]

matplotlib.pyplot.ylim(0,5) 

因为我正在绘制一系列直方图,并且最大频率变化很大。

我的代码现在看起来像这样:

import matplotlib.pyplot as plt

for LIST in LISTS:
    plt.figure()
    plt.hist(LIST)
    plt.title('Title')
    plt.xlabel("x-axis [unit]")
    plt.ylabel("Frequency")
    plt.savefig('figures/'LIST.png')

如何定义 y 轴从 0 到 1.1 *(1 个 bin 中的最大频率)?

【问题讨论】:

    标签: python matplotlib histogram axis


    【解决方案1】:

    如果我理解正确,这就是您希望实现的目标?

    import matplotlib.pyplot as plt
    import numpy.random as nprnd
    import numpy as np
    
    LISTS = []
    
    #Generate data
    for _ in range(3):
        LISTS.append(nprnd.randint(100, size=100))
    
    #Find the maximum y value of every data set
    maxYs = [i[0].max() for i in map(plt.hist,LISTS)]
    print "maxYs:", maxYs
    
    #Find the largest y 
    maxY = np.max(maxYs)
    print "maxY:",maxY
    
    for LIST in LISTS:
        plt.figure()
        #Set that as the ylim
        plt.ylim(0,maxY)
        plt.hist(LIST)
        plt.title('Title')
        plt.xlabel("x-axis [unit]")
        plt.ylabel("Frequency")
        #Got rid of the safe function
    plt.show()
    

    生成最大 y 限制与 maxY 相同的图。还有一些调试输出:

    maxYs: [16.0, 13.0, 13.0]
    maxY: 16.0
    

    函数plt.hist() 返回一个带有x, y 数据集的元组。因此,您可以致电y.max() 以获取每组的最大值。 Source.

    【讨论】:

    • 不完全,但它确实解决了我的问题。我正在寻找术语 maxY。我现在要做的就是将 maxY 乘以 1.1,以使 Y 轴比我的最大 Y 值长 10%。谢谢!
    猜你喜欢
    • 2017-04-11
    • 2015-10-11
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2015-07-10
    • 2020-03-28
    相关资源
    最近更新 更多