グラフを描きたい!と思ってまず思い浮かんだのがRとPythonの2つだったんですが、Rは過去に使ったことがあったので今回はPythonでチャレンジしてみました。
Pythonの場合はmatplotlibを使うことでグラフが描画できるらしいことが書いてあったので、まずは使い慣れているapt-getで環境が整備できるのか試してみました。
手元にあったUbuntu12でmatplotlibを検索してみます。
$ apt-cache search matplotlib
python-matplotlib - Python based plotting system in a style similar to Matlab
python-matplotlib-data - Python based plotting system (data package)
python-matplotlib-dbg - Python based plotting system (debug extension)
python-matplotlib-doc - Python based plotting system (documentation package)
python-mpltoolkits.basemap - matplotlib toolkit to plot on map projections
python-mpltoolkits.basemap-data - matplotlib toolkit to plot on map projections (data package)
python-mpltoolkits.basemap-doc - matplotlib toolkit to plot on map projections (documentation)
python-scitools - Python library for scientific computing
python-wxmpl - Painless matplotlib embedding in wxPython
python-mpmath - library for arbitrary-precision floating-point arithmetic
python-mpmath-doc - library for arbitrary-precision floating-point arithmetic - Documentation
結果を見る限りUbuntu12の場合はmatplotlibはPython2のみしか提供されていないようです。Ubuntu14であればPython3も整備されているみたいですが…。
という訳でPython2でmatplotlib
python-matplotlib
をインストールします。ちなみにUbuntu12でインストールされるPython2のバージョンは2.7.3
です。
$ sudo apt-get install python-matplotlib
すんなりとインストールできましたので、Pyplot tutorial にある以下のサンプルをゲットして…。
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
実行してみます。
$ python pyplot_simple.py
Traceback (most recent call last):
File "pyplot_simple.py", line 3, in <module>
import matplotlib.pyplot as plt
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 95, in <module>
new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 8, in <module>
import Tkinter as Tk, FileDialog
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 42, in <module>
raise ImportError, str(msg) + ', please install the python-tk package'
ImportError: No module named _tkinter, please install the python-tk package
エラーみたいですね。メッセージを読んでみるとpython-tk
をインストールしてねっ。みたいな事が書いてあるのでインストールします。
$ sudo apt-get install python-tk
表示されました!もっと苦戦するかと思ったのですが思ったよりもすんなりといけました。パッケージが用意されていたおかげですね。
もうちょっと複雑なグラフ
もうちょい複雑そうなdate_demo.py を試してみます。ソースは以下のようになっています。
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
# load a numpy record array from yahoo csv data with fields date,
# open, close, volume, adj_close from the mpl-data/example directory.
# The record array stores python datetime.date as an object array in
# the date column
datafile = cbook.get_sample_data('goog.npy')
try:
# Python3 cannot load python2 .npy files with datetime(object) arrays
# unless the encoding is set to bytes. Hovever this option was
# not added until numpy 1.10 so this example will only work with
# python 2 or with numpy 1.10 and later.
r = np.load(datafile, encoding='bytes').view(np.recarray)
except TypeError:
r = np.load(datafile).view(np.recarray)
fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)
# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
datemin = datetime.date(r.date.min().year, 1, 1)
datemax = datetime.date(r.date.max().year + 1, 1, 1)
ax.set_xlim(datemin, datemax)
# format the coords message box
def price(x):
return '$%1.2f' % x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
plt.show()
実行してみると…
$ python date_demo.py
Traceback (most recent call last):
File "t2.py", line 17, in <module>
datafile = cbook.get_sample_data('goog.npy')
File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 682, in get_sample_data
return open(f, 'rb')
IOError: [Errno 2] No such file or directory: "/etc/'/usr/share/matplotlib/sampledata'/goog.npy"
エラーのようです。/etc/'/usr/share/matplotlib/sampledata'/goog.npy
というおかしなパスを参照しているようです。どこかで設定するところのがあるんでしょうか…残念ながらまだそこまでの知識がないのでとりあえずgoog.npyを探してみます。
$ find /usr -name "goog.npy"
/usr/share/matplotlib/sampledata/goog.npy
見つかりましたので、フルパスに変更して…
@@ -12,7 +12,7 @@ yearsFmt = mdates.DateFormatter('%Y')
# open, close, volume, adj_close from the mpl-data/example directory.
# The record array stores python datetime.date as an object array in
# the date column
-datafile = cbook.get_sample_data('goog.npy')
+datafile = cbook.get_sample_data('/usr/share/matplotlib/sampledata/goog.npy')
try:
# Python3 cannot load python2 .npy files with datetime(object) arrays
# unless the encoding is set to bytes. Hovever this option was
再度実行してみます。
$ python date_demo.py
表示されました!思ったよりも簡単にグラフが描けたものの、今回はサンプルデータのパスの問題でしたが、それ以外で問題が起きるかもしれないと思うとちょっと不安を感じさせる結果となってしまいました。