logo

Matplotlib를 사용하여 Python에서 히스토그램 그리기

히스토그램은 데이터 시각화의 기본 도구로, 데이터 분포를 그래픽으로 표현합니다. 이는 수치 측정이나 센서 판독값과 같은 연속 데이터를 탐색하는 데 특히 유용합니다. 이 기사에서는 Plot Histogram 프로세스를 안내합니다. 파이썬 사용하여 Matplotlib , 데이터 준비부터 히스토그램 플롯 생성까지의 필수 단계를 다룹니다.

Matplotlib 히스토그램이란 무엇입니까?

히스토그램 일부 그룹 형태로 제공되는 데이터를 나타냅니다. 이는 수치 데이터 분포를 그래픽으로 표현하는 정확한 방법입니다. X축은 빈 범위를 나타내고 Y축은 빈도에 대한 정보를 제공하는 일종의 막대 그래프입니다.



Matplotlib 히스토그램 만들기

Matplotlib 히스토그램을 생성하기 위한 첫 번째 단계는 범위의 저장소를 생성한 다음 전체 값 범위를 일련의 간격으로 배포하고 각 간격에 속하는 값을 계산하는 것입니다. 구간은 연속적이고 겹치지 않는 변수 간격으로 식별됩니다. matplotlib.pyplot.hist() 함수는 x의 히스토그램을 계산하고 생성하는 데 사용됩니다.

다음 표는 matplotlib.pyplot.hist() 함수에서 허용하는 매개변수를 보여줍니다.

기인하다 매개변수
엑스 배열 또는 배열의 시퀀스
쓰레기통 선택적 매개변수에는 정수, 시퀀스 또는 문자열이 포함됩니다.
밀도 선택적 매개변수에는 부울 값이 포함되어 있습니다.
범위 선택적 매개변수는 빈의 상한 및 하한 범위를 나타냅니다.
히스트 유형 히스토그램 유형[bar, barstacked, step, stepfilled]을 생성하는 데 사용되는 선택적 매개변수, 기본값은 막대입니다.
맞추다 선택적 매개변수는 히스토그램 [왼쪽, 오른쪽, 중간]의 플롯을 제어합니다.
무게 선택적 매개변수에는 x와 동일한 차원을 갖는 가중치 배열이 포함됩니다.
맨 아래 각 bin의 기준선 위치
너비 빈 너비에 대한 막대의 상대적 너비인 선택적 매개변수
색상 색상이나 색상 사양의 순서를 설정하는 데 사용되는 선택적 매개변수
상표 여러 데이터세트와 일치시킬 선택적 매개변수 문자열 또는 문자열 시퀀스
통나무 로그 스케일에서 히스토그램 축을 설정하는 데 사용되는 선택적 매개변수

Matplotlib을 사용하여 Python에서 히스토그램 그리기

여기에서는 Matplotlib에서 히스토그램을 그리는 다양한 방법을 살펴보겠습니다. 파이썬 :



  • 기본 히스토그램
  • 밀도 도표를 사용한 맞춤형 히스토그램
  • 워터마크가 포함된 맞춤형 히스토그램
  • 서브플롯이 포함된 다중 히스토그램
  • 누적 히스토그램
  • 2D 히스토그램(Hexbin 플롯)

Matplotlib에서 기본 히스토그램 만들기

Python을 사용하여 임의의 값을 사용하여 Matplotlib에서 기본 히스토그램을 만들어 보겠습니다.

100만 몇 0

파이썬3






import> matplotlib.pyplot as plt> import> numpy as np> # Generate random data for the histogram> data>=> np.random.randn(>1000>)> # Plotting a basic histogram> plt.hist(data, bins>=>30>, color>=>'skyblue'>, edgecolor>=>'black'>)> # Adding labels and title> plt.xlabel(>'Values'>)> plt.ylabel(>'Frequency'>)> plt.title(>'Basic Histogram'>)> # Display the plot> plt.show()>

>

>

산출:

Matplotlib을 사용하는 Python의 히스토그램

밀도 플롯을 사용한 Matplotlib의 사용자 정의 히스토그램

Python에서 Matplotlib과 Seaborn을 사용하여 밀도 플롯이 포함된 맞춤형 히스토그램을 만들어 보겠습니다. 결과 플롯은 매끄러운 밀도 추정을 통해 무작위 데이터의 분포를 시각화합니다.

파이썬3




import> matplotlib.pyplot as plt> import> seaborn as sns> import> numpy as np> # Generate random data for the histogram> data>=> np.random.randn(>1000>)> # Creating a customized histogram with a density plot> sns.histplot(data, bins>=>30>, kde>=>True>, color>=>'lightgreen'>, edgecolor>=>'red'>)> # Adding labels and title> plt.xlabel(>'Values'>)> plt.ylabel(>'Density'>)> plt.title(>'Customized Histogram with Density Plot'>)> # Display the plot> plt.show()>

>

자바 프로그래밍의 객체
>

산출:

히스토그램 Matplotlib

워터마크가 포함된 맞춤형 히스토그램

Python에서 Matplotlib을 사용하여 특정 기능을 갖춘 맞춤형 히스토그램을 만듭니다. 여기에는 축 눈금 제거, 패딩 추가, 더 나은 시각화를 위한 색상 그라데이션 설정과 같은 추가 스타일링 요소가 포함되어 있습니다.

파이썬3




import> matplotlib.pyplot as plt> import> numpy as np> from> matplotlib>import> colors> from> matplotlib.ticker>import> PercentFormatter> # Creating dataset> np.random.seed(>23685752>)> N_points>=> 10000> n_bins>=> 20> # Creating distribution> x>=> np.random.randn(N_points)> y>=> .>8> *>*> x>+> np.random.randn(>10000>)>+> 25> legend>=> [>'distribution'>]> # Creating histogram> fig, axs>=> plt.subplots(>1>,>1>,> >figsize>=>(>10>,>7>),> >tight_layout>=> True>)> # Remove axes splines> for> s>in> [>'top'>,>'bottom'>,>'left'>,>'right'>]:> >axs.spines[s].set_visible(>False>)> # Remove x, y ticks> axs.xaxis.set_ticks_position(>'none'>)> axs.yaxis.set_ticks_position(>'none'>)> > # Add padding between axes and labels> axs.xaxis.set_tick_params(pad>=> 5>)> axs.yaxis.set_tick_params(pad>=> 10>)> # Add x, y gridlines> axs.grid(b>=> True>, color>=>'grey'>,> >linestyle>=>'-.'>, linewidth>=> 0.5>,> >alpha>=> 0.6>)> # Add Text watermark> fig.text(>0.9>,>0.15>,>'Jeeteshgavande30'>,> >fontsize>=> 12>,> >color>=>'red'>,> >ha>=>'right'>,> >va>=>'bottom'>,> >alpha>=> 0.7>)> # Creating histogram> N, bins, patches>=> axs.hist(x, bins>=> n_bins)> # Setting color> fracs>=> ((N>*>*>(>1> /> 5>))>/> N.>max>())> norm>=> colors.Normalize(fracs.>min>(), fracs.>max>())> for> thisfrac, thispatch>in> zip>(fracs, patches):> >color>=> plt.cm.viridis(norm(thisfrac))> >thispatch.set_facecolor(color)> # Adding extra features> plt.xlabel(>'X-axis'>)> plt.ylabel(>'y-axis'>)> plt.legend(legend)> plt.title(>'Customized histogram'>)> # Show plot> plt.show()>

>

>

출력 :

Matplotlib을 사용한 히스토그램

서브플롯이 포함된 다중 히스토그램

Python에서 Matplotlib을 사용하여 두 개의 히스토그램을 나란히 생성해 보겠습니다. 각 히스토그램에는 자체 무작위 데이터 세트가 있으며 분포에 대한 시각적 비교를 제공합니다.data1>그리고data2>히스토그램을 사용합니다.

파이썬3




import> matplotlib.pyplot as plt> import> numpy as np> # Generate random data for multiple histograms> data1>=> np.random.randn(>1000>)> data2>=> np.random.normal(loc>=>3>, scale>=>1>, size>=>1000>)> # Creating subplots with multiple histograms> fig, axes>=> plt.subplots(nrows>=>1>, ncols>=>2>, figsize>=>(>12>,>4>))> axes[>0>].hist(data1, bins>=>30>, color>=>'Yellow'>, edgecolor>=>'black'>)> axes[>0>].set_title(>'Histogram 1'>)> axes[>1>].hist(data2, bins>=>30>, color>=>'Pink'>, edgecolor>=>'black'>)> axes[>1>].set_title(>'Histogram 2'>)> # Adding labels and title> for> ax>in> axes:> >ax.set_xlabel(>'Values'>)> >ax.set_ylabel(>'Frequency'>)> # Adjusting layout for better spacing> plt.tight_layout()> # Display the figure> plt.show()>

>

>

산출:

스크린샷-2023-12-05-222526

Matplotlib을 사용한 누적 히스토그램

Python에서 Matplotlib을 사용하여 서로 다른 무작위 데이터 분포를 갖는 두 개의 데이터 세트를 나타내는 누적 히스토그램을 생성해 보겠습니다. 누적 히스토그램은 두 데이터 세트의 결합된 빈도 분포에 대한 통찰력을 제공합니다.

파이썬3


라텍스 텍스트 크기



import> matplotlib.pyplot as plt> import> numpy as np> # Generate random data for stacked histograms> data1>=> np.random.randn(>1000>)> data2>=> np.random.normal(loc>=>3>, scale>=>1>, size>=>1000>)> # Creating a stacked histogram> plt.hist([data1, data2], bins>=>30>, stacked>=>True>, color>=>[>'cyan'>,>'Purple'>], edgecolor>=>'black'>)> # Adding labels and title> plt.xlabel(>'Values'>)> plt.ylabel(>'Frequency'>)> plt.title(>'Stacked Histogram'>)> # Adding legend> plt.legend([>'Dataset 1'>,>'Dataset 2'>])> # Display the plot> plt.show()>

>

>

산출:

스크린샷-2023-12-05-222933

Matplotlib를 사용하여 2D 히스토그램(Hexbin Plot) 플롯

Python에서 Matplotlib을 사용하여 2D hexbin 플롯을 생성하고 육각형이 데이터 포인트의 밀도를 전달하는 2D 데이터 분포의 시각적 표현을 제공합니다. 컬러바는 플롯의 다양한 영역에 있는 점의 밀도를 해석하는 데 도움이 됩니다.

파이썬3




import> matplotlib.pyplot as plt> import> numpy as np> # Generate random 2D data for hexbin plot> x>=> np.random.randn(>1000>)> y>=> 2> *> x>+> np.random.normal(size>=>1000>)> # Creating a 2D histogram (hexbin plot)> plt.hexbin(x, y, gridsize>=>30>, cmap>=>'Blues'>)> # Adding labels and title> plt.xlabel(>'X values'>)> plt.ylabel(>'Y values'>)> plt.title(>'2D Histogram (Hexbin Plot)'>)> # Adding colorbar> plt.colorbar()> # Display the plot> plt.show()>

자바는 다음을 가지고

>

>

산출:

스크린샷-2023-12-05-222826

결론

Matplotlib 히스토그램을 그리는 것은 간단하고 간단한 프로세스입니다. 을 사용하여hist()>함수를 사용하면 다양한 빈 너비와 빈 가장자리를 사용하여 히스토그램을 쉽게 만들 수 있습니다. 필요에 따라 히스토그램의 모양을 사용자 정의할 수도 있습니다.