今回は、matplotlibのプロットでグリッドラインを追加する方法を学びます。
matplotlibはpythonのプロットライブラリで、科学的なプロットやグラフを作成するための対話的な環境を提供しています。
さっそく本題に入りましょう。
Matplot lib のプロットにグリッド線を追加する ## Steps to add grid lines to Matplot lib plots
それでは、matplotlib のプロットにグリッド線を追加する手順を説明します。
この記事もチェック:Pythonとmatplotlibでエラーバーのグラフを作成する方法
1. モジュールのインストール
matplotlib – (英語)
pip install matplotlib |
パイプロット
pyplot サブモジュールは matplotlib の機能の大部分を含んでいます
注意:通常、コンパイラはグラフを表示する機能を持っていませんが、Pythonでは、数行のコードを追加することで互換性を持たせることができます。
import sys
import matplotlib
matplotlib.use( 'Agg' )
# matplotlib relies on a backend to render the plots and here ‘Agg’ is the default backend import matplotlib.pyplot as pyt
# lines of code for plotting a graph pyt.savefig(sys.stdout. buffer )
sys.stdout.flush() # these two lines are used to avoid excess buffering and print the data without any delay and make sure the code works |
例えば、以下の様になります。
import sys
import matplotlib
matplotlib.use( 'Agg' )
# matplotlib relies on a backend to render the plots and here ‘Agg’ is the default backend import matplotlib.pyplot as pyt
import numpy as np
x = np.array([ 0 , 10 ])
y = np.array([ 0 , 200 ])
pyt.plot(x, y) pyt.show() pyt.savefig(sys.stdout. buffer )
sys.stdout.flush() |
x = np.array([ 0 , 10 ])
y = np.array([ 0 , 200 ])
pyt.title( "Sales of Ice Cream" )
# to represent the title on the plot pyt.xlabel( "Days" ) # to label the x-axis
pyt.ylabel( "Customers" ) # to label the y-axis
pyt.plot(x, y) pyt.grid() pyt.show() |
2. プロットにグリッド線を追加する
Pyplot で grid() 関数を使うと、プロットにグリッド線を追加することができます。
例えば、以下の様になります。
pyt.grid(axis = ‘y’)
|
pyt.grid(axis = ‘x’) |
3. 表示するグリッド線を指定する
grid()関数のaxisパラメータを使って、表示するグリッド線を指定することができます。
指定できる値は、’x’、’y’、’both’です。
x’、’y’、’both’ のいずれかです。
しかし、デフォルトは’both’なので、書かないようにすればよいでしょう。
例えば、以下の様になります。
- x 軸のグリッド線のみを表示します。
pyt.grid(color = 'red' , linestyle = '--' , linewidth = 0.75 , axis = 'both' )
|

- Y 軸のグリッド線のみを表示します。


4. グリッドのラインプロパティを設定する
グリッドのプロパティを色やスタイルなど様々な方法で設定することができます。
ここではスタイリングを次のように定義する: color= ‘specify_color’, linestyle=’specify_linestyle’, linewidth= number, axis=’specify_axis(‘x’,’y’ or ‘both’)’.
例えば


まとめ
チュートリアルは以上です。
Pythonでグリッド線を描く方法と、matplotlibライブラリを使ったグリッド線の様々な特性について、よく理解していただけたと思います。
今後もAsk PythonでPythonのチュートリアルを続けていきます。