ヒストグラムはデータ視覚化の基本ツールであり、データの分布をグラフで表現します。これらは、数値測定やセンサー読み取り値などの連続データを調査する場合に特に役立ちます。この記事では、ヒストグラムをプロットするプロセスについて説明します。 パイソン を使用して マットプロットリブ では、データの準備からヒストグラム プロットの生成までの重要な手順を説明します。
Matplotlib ヒストグラムとは何ですか?
あ ヒストグラム は、いくつかのグループの形式で提供されるデータを表します。これは、数値データの分布をグラフで表現するための正確な方法です。これは棒グラフの一種で、X 軸がビンの範囲を表し、Y 軸が周波数に関する情報を示します。
Matplotlib ヒストグラムの作成
Matplotlib ヒストグラムを作成するには、最初の手順として範囲のビンを作成し、次に値の範囲全体を一連の間隔に分配し、各間隔に該当する値をカウントします。ビンは、変数の連続した重複しない間隔として識別されます。 matplotlib.pyplot.hist() 関数は、x のヒストグラムを計算して作成するために使用されます。
次の表は、 matplotlib.pyplot.hist() 関数で受け入れられるパラメーターを示しています。
| 属性 | パラメータ |
|---|---|
| バツ | 配列または配列のシーケンス |
| ゴミ箱 | オプションのパラメータには整数、シーケンス、または文字列が含まれています |
| 密度 | オプションのパラメータにはブール値が含まれます |
| 範囲 | オプションのパラメータはビンの上限と下限の範囲を表します |
| ヒストタイプ | ヒストグラムのタイプ [bar、barstacked、step、stepfilled] を作成するために使用されるオプションのパラメーター、デフォルトは bar です |
| 整列する | オプションのパラメータは、ヒストグラムのプロットを制御します [左、右、中央] |
| 重み | オプションのパラメータには、x と同じ次元を持つ重みの配列が含まれます |
| 底 | 各ビンのベースラインの位置 |
| 幅 | ビンの幅に対するバーの相対的な幅を示すオプションのパラメータ |
| 色 | 色または色の仕様のシーケンスを設定するために使用されるオプションのパラメータ |
| ラベル | 複数のデータセットと一致するオプションのパラメータ文字列または文字列のシーケンス |
| ログ | 対数スケールでヒストグラムの軸を設定するために使用されるオプションのパラメータ |
Matplotlib を使用した Python でのヒストグラムのプロット
ここでは、Matplotlib でヒストグラムをプロットするさまざまな方法を見ていきます。 パイソン :
- 基本的なヒストグラム
- 密度プロットを使用したカスタマイズされたヒストグラム
- ウォーターマーク付きのカスタマイズされたヒストグラム
- サブプロットを含む複数のヒストグラム
- 積み上げヒストグラム
- 2D ヒストグラム (Hexbin プロット)
Matplotlib で基本的なヒストグラムを作成する
Python を使用して、いくつかのランダムな値の基本的なヒストグラムを Matplotlib で作成してみましょう。
Javaのwhile条件
Python3
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 と Seaborn を使用して、密度プロットを含むカスタマイズされたヒストグラムを作成してみましょう。結果として得られるプロットは、滑らかな密度推定を使用してランダム データの分布を視覚化します。
Python3
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()> |
>
>
出力:

ウォーターマーク付きのカスタマイズされたヒストグラム
特定の機能を備えた Python の Matplotlib を使用して、カスタマイズされたヒストグラムを作成します。これには、軸目盛りの削除、パディングの追加、視覚化を向上させるための色のグラデーションの設定など、追加のスタイル要素が含まれています。
Python3
Javaオブジェクト
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()> |
>
>
出力:

サブプロットを含む複数のヒストグラム
Python の Matplotlib を使用して 2 つのヒストグラムを並べて生成してみましょう。それぞれに独自のランダム データのセットがあり、ヒストグラムの分布を視覚的に比較できます。data1>そしてdata2>ヒストグラムを使用します。
Python3
csma と csma cd
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()> |
>
>
出力:

Matplotlib を使用した積み上げヒストグラム
Python の Matplotlib を使用して、異なるランダム データ分布を持つ 2 つのデータセットを表す積み上げヒストグラムを生成してみましょう。積み上げヒストグラムは、2 つのデータセットを組み合わせた度数分布についての洞察を提供します。
Python3
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()> |
>
>
出力:

Matplotlib を使用した 2D ヒストグラム (Hexbin プロット) のプロット
Python の Matplotlib を使用して 2D ヘックスビン プロットを生成して、2D データ分布を視覚的に表現します。六角形はデータ ポイントの密度を表します。カラーバーは、プロットのさまざまな領域の点の密度を解釈するのに役立ちます。
Python3
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()> |
文字列をJavaと比較する
>
>
出力:

結論
Matplotlib ヒストグラムのプロットは、シンプルで簡単なプロセスです。を使用することで、hist()>関数を使用すると、異なるビン幅とビンのエッジを持つヒストグラムを簡単に作成できます。ニーズに合わせてヒストグラムの外観をカスタマイズすることもできます