IT

Matplotlib의 빈 크기 (히스토그램)

lottoking 2020. 7. 5. 07:45
반응형

Matplotlib의 빈 크기 (히스토그램)


히스토그램을 만들기 위해 matplotlib을 사용하고 있습니다.

기본적으로 빈 수와 달리 빈 크기를 수동으로 설정하는 방법이 있는지 궁금합니다.

어떤 아이디어를 가진 사람은 대단히 감사합니다.

감사


실제로는 매우 쉽습니다. 빈 수 대신 빈 경계가있는 목록을 제공 할 수 있습니다. 그것들은 또한 불균등하게 분배 될 수 있습니다 :

plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])

당신이 그것들을 균등하게 분배하기를 원한다면, 간단히 range를 사용할 수 있습니다 :

plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))

원래 답변에 추가

위의 줄은 data정수 채워진 경우에만 작동 합니다. 으로 macrocosme는 지적 수레를 위해 당신은 사용할 수 있습니다 :

import numpy as np
plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))

N 빈의 경우 빈 가장자리는 N + 1 값 목록으로 지정되며, 첫 번째 N은 낮은 빈 가장자리를, +1은 마지막 빈의 상단을 나타냅니다.

암호:

from numpy import np; from pylab import *

bin_size = 0.1; min_edge = 0; max_edge = 2.5
N = (max_edge-min_edge)/bin_size; Nplus1 = N + 1
bin_list = np.linspace(min_edge, max_edge, Nplus1)

linspace는 min_edge에서 max_edge까지 배열을 N + 1 값 또는 N 구간으로 나눈다는 점에 유의하십시오.


쉬운 방법은 가지고있는 데이터의 최소 및 최대를 계산 한 다음 계산하는 것 L = max - min입니다. 그런 다음 L원하는 빈 너비로 나눕니다 (빈 크기가 의미하는 것으로 가정합니다).이 값의 상한을 빈 수로 사용하십시오.


OP와 같은 문제가 있었지만 Lastalda가 지정한 방식으로 작동하지 못했습니다. 나는 질문을 올바르게 해석했는지 알지 못하지만 다른 해결책을 찾았습니다 (아마도 그것을하는 것은 정말 나쁜 방법 일 것입니다).

이것이 내가 한 방식입니다.

plt.hist([1,11,21,31,41], bins=[0,10,20,30,40,50], weights=[10,1,40,33,6]);

이것은 이것을 만듭니다 :

matplotlib에서 작성된 히스토그램 그래프를 보여주는 이미지

따라서 첫 번째 매개 변수는 기본적으로 bin을 초기화합니다. 특히 bins 매개 변수에서 설정 한 범위 사이의 숫자를 만듭니다.

To demonstrate this, look at the array in the first parameter ([1,11,21,31,41]) and the 'bins' array in the second parameter ([0,10,20,30,40,50]):

  • The number 1 (from the first array) falls between 0 and 10 (in the 'bins' array)
  • The number 11 (from the first array) falls between 11 and 20 (in the 'bins' array)
  • The number 21 (from the first array) falls between 21 and 30 (in the 'bins' array), etc.

Then I'm using the 'weights' parameter to define the size of each bin. This is the array used for the weights parameter: [10,1,40,33,6].

So the 0 to 10 bin is given the value 10, the 11 to 20 bin is given the value of 1, the 21 to 30 bin is given the value of 40, etc.


I like things to happen automatically and for bins to fall on "nice" values. The following seems to work quite well.

import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
def compute_histogram_bins(data, desired_bin_size):
    min_val = np.min(data)
    max_val = np.max(data)
    min_boundary = -1.0 * (min_val % desired_bin_size - min_val)
    max_boundary = max_val - max_val % desired_bin_size + desired_bin_size
    n_bins = int((max_boundary - min_boundary) / desired_bin_size) + 1
    bins = np.linspace(min_boundary, max_boundary, n_bins)
    return bins

if __name__ == '__main__':
    data = np.random.random_sample(100) * 123.34 - 67.23
    bins = compute_histogram_bins(data, 10.0)
    print(bins)
    plt.hist(data, bins=bins)
    plt.xlabel('Value')
    plt.ylabel('Counts')
    plt.title('Compute Bins Example')
    plt.grid(True)
    plt.show()

결과는 빈 크기 간격마다 빈이 있습니다.

[-70. -60. -50. -40. -30. -20. -10.   0.  10.  20.  30.  40.  50.  60.]

계산 된 빈 히스토그램


용기를 균일하게하고 샘플에 맞게 Quantile을 사용합니다.

bins=df['Generosity'].quantile([0,.05,0.1,0.15,0.20,0.25,0.3,0.35,0.40,0.45,0.5,0.55,0.6,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]).to_list()

plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')

여기에 이미지 설명을 입력하십시오


정수 x 값을 가진 히스토그램의 경우

plt.hist(data, np.arange(min(data)-0.5, max(data)+0.5))
plt.xticks(range(min(data), max(data)))

오프셋 0.5는 빈을 x 축 값의 중심에 둡니다. plt.xticks호출은 모든 정수에 틱을 추가합니다.

참고 URL : https://stackoverflow.com/questions/6986986/bin-size-in-matplotlib-histogram

반응형