복붙노트

[PYTHON] 히스토그램 Matplotlib

PYTHON

히스토그램 Matplotlib

그래서 약간의 문제가 있습니다. 데이터를 이미 히스토그램 형식으로 된 scipy로 설정 했으므로 빈의 중심과 빈당 이벤트 수가 늘어납니다. 이제 어떻게 플롯을 히스토그램으로 사용할 수 있습니까? 나는 단지 해보려고 노력했다.

bins, n=hist()

그러나 그것은 그것을 좋아하지 않았습니다. 어떤 추천?

해결법

  1. ==============================

    1.

    import matplotlib.pyplot as plt
    import numpy as np
    
    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(10000)
    hist, bins = np.histogram(x, bins=50)
    width = 0.7 * (bins[1] - bins[0])
    center = (bins[:-1] + bins[1:]) / 2
    plt.bar(center, hist, align='center', width=width)
    plt.show()
    

    객체 지향 인터페이스는 또한 간단합니다.

    fig, ax = plt.subplots()
    ax.bar(center, hist, align='center', width=width)
    fig.savefig("1.png")
    

    커스텀 (비등 상) 빈을 사용하고 있다면, np.diff를 사용하여 너비를 전달하고 너비를 ax.bar에 전달하고 ax.set_xticks를 사용하여 빈 가장자리에 라벨을 붙일 수 있습니다 :

    import matplotlib.pyplot as plt
    import numpy as np
    
    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(10000)
    bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
    hist, bins = np.histogram(x, bins=bins)
    width = np.diff(bins)
    center = (bins[:-1] + bins[1:]) / 2
    
    fig, ax = plt.subplots(figsize=(8,3))
    ax.bar(center, hist, align='center', width=width)
    ax.set_xticks(bins)
    fig.savefig("/tmp/out.png")
    
    plt.show()
    

  2. ==============================

    2.막대를 원하지 않으면 다음과 같이 플롯 할 수 있습니다.

    막대를 원하지 않으면 다음과 같이 플롯 할 수 있습니다.

    import numpy as np
    import matplotlib.pyplot as plt
    
    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(10000)
    
    bins, edges = np.histogram(x, 50, normed=1)
    left,right = edges[:-1],edges[1:]
    X = np.array([left,right]).T.flatten()
    Y = np.array([bins,bins]).T.flatten()
    
    plt.plot(X,Y)
    plt.show()
    

  3. ==============================

    3.나는 이것이 당신의 질문에 대답하지 않는다는 것을 알고 있지만, 히스토그램에 대한 matplotlib 솔루션을 검색 할 때이 페이지에서 끝납니다. 왜냐하면 간단한 histogram_demo가 matplotlib 예제 갤러리 페이지에서 제거 되었기 때문입니다.

    나는 이것이 당신의 질문에 대답하지 않는다는 것을 알고 있지만, 히스토그램에 대한 matplotlib 솔루션을 검색 할 때이 페이지에서 끝납니다. 왜냐하면 간단한 histogram_demo가 matplotlib 예제 갤러리 페이지에서 제거 되었기 때문입니다.

    다음은 numpy를 가져올 필요가없는 솔루션입니다. 필자는 데이터 x를 생성하기 위해 numpy를 가져 오기만하면됩니다. @unutbu의 답과 같이 함수 막대 대신 함수 hist에 의존합니다.

    import numpy as np
    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(10000)
    
    import matplotlib.pyplot as plt
    plt.hist(x, bins=50)
    plt.savefig('hist.png')
    

    또한 matplotlib 갤러리와 matplotlib 예제를 확인하십시오.

  4. ==============================

    4.판다를 기꺼이 사용한다면 :

    판다를 기꺼이 사용한다면 :

    pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')
    
  5. ==============================

    5.나는 이것이 누군가에게 유용 할 것이라고 생각한다.

    나는 이것이 누군가에게 유용 할 것이라고 생각한다.

    Numpy의 히스토그램 기능은 내 귀찮은 부분 (비록 그럴만 한 이유가 있음에도 불구하고)으로, bin의 값보다는 각 bin의 가장자리를 되 돌린다. 그러나 이것은 간격 내에 놓일 수있는 부동 소수점 숫자에 의미가 있습니다 (즉, 중심 값은 매우 의미가 없습니다). 이산 값 또는 정수 (0, 1, 2 등)를 처리 할 때 원하는 출력이 아닙니다. . 특히, np.histogram에서 반환되는 bin의 길이는 counts / density의 길이와 동일하지 않습니다.

    이 문제를 해결하기 위해 np.digitize를 사용하여 입력을 양자화하고 이산 수의 빈을 각 빈의 카운트 수와 함께 반환했습니다. 카운트의 정수를 얻기 위해 쉽게 편집 할 수 있습니다.

    def compute_PMF(data)
        import numpy as np
        from collections import Counter
        _, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
        h = Counter(np.digitize(data,bins) - 1)
        weights = np.asarray(list(h.values())) 
        weights = weights / weights.sum()
        values = np.asarray(list(h.keys()))
        return weights, values
    ####
    

    참고 문헌 :

    [1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

    [2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html

  6. from https://stackoverflow.com/questions/5328556/histogram-matplotlib by cc-by-sa and MIT license