pythonでグラフを描画(matplotlib)

グラフの例(sin関数)

【Python入門】ライブラリmatplotlibの基本的な使い方 - Qiita

[~/git/work/src/python] $ cat test.py
import math
import numpy as np
from matplotlib import pyplot

pi = math.pi

x = np.linspace(0, 2*pi, 100)
y = np.sin(x)

pyplot.plot(x, y)
pyplot.show()
[~/git/work/src/python] $ 

実行

python3 test.py 

f:id:ludwig125:20171207010603p:plain

以下、これを表示するまでのエラー

エラー対応

参考

matplotlibが描画されない - DISTRICT 37

python - python3 で _tkinter を import したい - スタック・オーバーフロー

ImportError:
Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
If you're working with a numpy git repo, try `git clean -xdf` (removes all
files not under version control).  Otherwise reinstall numpy.

Original error was: /usr/local/lib/python2.7/dist-packages/numpy/core/multiarray.so: undefined symbo
l: _Py_ZeroStruct

[~/git/work/src/python/software-design/saikyu-kouka] $ pip3 install numpy
Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 7, in <module>
    from pip import main
  File "/usr/local/lib/python3.6/site-packages/pip/__init__.py", line 26, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "/usr/local/lib/python3.6/site-packages/pip/utils/__init__.py", line 16, in <module>
    import subprocess
  File "/usr/local/lib/python3.6/subprocess.py", line 136, in <module>
    import _posixsubprocess
ImportError: /usr/local/lib/python2.7/dist-packages/_posixsubprocess.so: undefined symbol: Py_InitMo
dule4_64


や

 Traceback (most recent call last):
  File "test.py", line 3, in <module>
    from matplotlib import pyplot
  File "/usr/local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 113, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/usr/local/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 60, in pylab_setup
    [backend_name], 0)
  File "/usr/local/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py", line 6, in <module>
    from six.moves import tkinter as Tk
  File "/usr/local/lib/python2.7/dist-packages/six.py", line 92, in __get__
    result = self._resolve()
  File "/usr/local/lib/python2.7/dist-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/usr/local/lib/python2.7/dist-packages/six.py", line 82, in _import_module
    __import__(name)
  File "/usr/local/lib/python3.6/tkinter/__init__.py", line 36, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

などのエラーが出た

もう面倒になったので、pyenvをつくって、入れ直した

$ sudo apt install python3-pip python3-dev

$ pyenv install 3.5.4
$ pyenv local 3.5.4
$ pyenv versions
  system
* 3.5.4 (set by /home/ludwig125/git/work/src/python/.python-version)
$ 

python3のパスを確認

$ which python3
/home/ludwig125/.pyenv/shims/python3
$ /home/ludwig125/.pyenv/shims/python3 --version
Python 3.5.4
$ 

追加で必要なライブラリをインストール

$ python3 -m pip install numpy
$ python3 -m pip install matplotlib

tkinterが使えることを確認

$ python3 -m tkinter

f:id:ludwig125:20171207011158p:plain

グラフの例(1次関数)

$ cat y-is-10x.py 
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 99, 100)

y = x * 10

plt.plot(x, y)
plt.show()

実行結果

 $ python3  y-is-10x.py 

f:id:ludwig125:20171207012956p:plain

グラフの例(ノイズの入った1次関数)

$ cat noisy_y.py 
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 99, 100)

f_noisy = np.vectorize(lambda x: x * 10 + np.random.normal(0, 100))
d = f_noisy(x)

plt.plot(x, d)
plt.show()

実行結果

python3 noisy_y.py 

f:id:ludwig125:20171207013117p:plain

グラフの例(放物線)

$ cat throw.py 

from math import sin, cos, radians
from matplotlib import pyplot as plt

def throw(x, y, v0, angle, repeatNum, dt):
    isSuccess = False
    xarray = []; yarray = []
    vx = v0*cos( radians(angle) )
    vy = v0*sin( radians(angle) )
    ax = 0.0
    ay = -9.8
    for i in range(repeatNum):
        x = x + (vx + ax*dt/2)*dt
        y = y + (vy + ay*dt/2)*dt
        vx = vx + ax * dt
        vy = vy + ay * dt
        xarray.append(x)
        yarray.append(y)
    return (xarray, yarray, isSuccess)

def prepareFigureArea():
    plt.figure(figsize=(5, 5))
    plt.xlim([0, 5])
    plt.ylim([0, 5])
    plt.xlabel('X - Axis (m)')
    plt.ylabel('Y - Axis (m)')
    return

x1, y1, isSuccess = throw(0, 0, 6, 35, 500, 0.01)
x2, y2, isSuccess2 = throw(0, 0, 6, 45, 500, 0.01)
x3, y3, isSuccess3 = throw(0, 0, 6, 55, 500, 0.01)
x4, y4, isSuccess3 = throw(0, 0, 6, 70, 500, 0.01)

prepareFigureArea()
plt.plot(x1, y1, 'bo-', x2, y2, 'ro-', x3, y3, 'ko-', x4, y4, 'yo-')
plt.legend(['35 deg.', '45 deg.', '55 deg.', '70 deg.'])
plt.show()

実行結果

python3 throw.py

以下が必要だったのでpip3 install

$ pip3 install six
$ pip3 install pyparsing
$ pip3 install cycler
$ pip3 install python-dateutil --upgrade

f:id:ludwig125:20171209004734p:plain

matplotlibの仕様

グラフの点や線の形

グラフの色

matplotlib参考