matplotlibを使ってみる

matplotlibを使ってみたメモです。
REPLで使ってみます。

動作確認

早速使ってみました。
が、下記を実行してみましたが、グラフが表示されません・・・

>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]
>>> y = [1,8,27,64]
>>> plt.plot(x,y)
[<matplotlib.lines.Line2D object at 0x7f584df7a898>]
>>> plt.show()
aggの設定

どうやら調べるとaggという描画ライブラリを使っているようですが、
TkAggというTclのTkインターフェースを使ったものに変更する必要があるようです。

aggをTkaggに変更するために設定ファイルを修正します。
REPLで下記を実行すると設定ファイルの場所が表示されます。

>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/root/.pyenv/versions/3.5.1/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc'

設定ファイルを修正し、aggをTkaggに変更します。

# vi /root/.pyenv/versions/3.5.1/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

#backend      : agg
backend      : Tkagg

tclとtkに必要なライブラリをyumでインストールします。

# yum install tcl
# yum install tcl-devel
# yum install tk
# yum install tk-devel
# yum install tkinter
# yum install python-matplotlib-tk

そのあとmatplotlibを再インストールすると表示されるようになりました。

# pip uninstall matplotlib
# pip install matplotlib
使い方

インポートして簡単なグラフを描画。
matplotlibはpltとしてimportするのが定石だそうです。
plot()でグラフ描画して、show()で画面表示します。

>>> import matplotlib.pyplot as plt

散布図

>>> x = [1,2,3,4]
>>> y = [1,8,27,64]
>>> plt.scatter(x,y)
<matplotlib.collections.PathCollection object at 0x7f584e005160>
>>> plt.show()

f:id:pppurple:20160213232031j:plain:w500


折れ線グラフ

>>> x = [1,2,3,4]
>>> y = [1,8,27,64]
>>> plt.plot(x,y)
>>> plt.show()

f:id:pppurple:20160213232041j:plain:w500


複数系列の散布図
赤(r)と水色(c)に出し分け。

>>> x1 = np.array([1,2,3])
>>> y1 = np.array([1,2,3])
>>> x2 = np.array([1,2,3])
>>> y2 = np.array([2,4,6])

>>> plt.scatter(x1,y1,c="r")
<matplotlib.collections.PathCollection object at 0x7f584d5a4e48>
>>> plt.scatter(x2,y2,c="c")
<matplotlib.collections.PathCollection object at 0x7f584d5aca20>
>>> plt.show()

f:id:pppurple:20160213232043j:plain:w500

プロットを"x"と"+"に出し分け。

>>> x1 = np.array([1,2,3])
>>> y1 = np.array([1,2,3])
>>> x2 = np.array([1,2,3])
>>> y2 = np.array([2,4,6])

>>> plt.scatter(x1,y1,marker="x",c="r")
<matplotlib.collections.PathCollection object at 0x7f584d4f1e48>
>>> plt.scatter(x2,y2,marker="+",c="c")
<matplotlib.collections.PathCollection object at 0x7f584d4f99e8>
>>> plt.show()

f:id:pppurple:20160213232047j:plain:w500


こんなとこです。


【参考】