TAKEC

大学院生の覚書

matplotlib で画像を保存

matplotlib で作成したグラフを保存する。

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

N = 256
n = np.linspace(0,N,N,False)
#w = 2*np.pi*n/(N-1)
w = 2*np.pi*n/N
# 7 term Blackman-Harris
window = (
        0.27105140069342
        -0.43329793923448*np.cos(w)
        +0.21812299954311*np.cos(2*w)
        -0.06592544638803*np.cos(3*w)
        +0.01081174209837*np.cos(4*w)
        -0.00077658482522*np.cos(5*w)
        +0.00001388721735*np.cos(6*w)
        )

# グラフのサイズを指定(1in=2.54cm)
fig = plt.figure(figsize=(8,2))
ax = fig.gca()
ax.set_xlim((0,2*np.pi))
ax.set_xticks(np.linspace(0, 2*np.pi, 11))
ax.set_xticklabels(["{0:.1f}$\pi$".format(x/np.pi) for x in ax.get_xticks()])
ax.set_xlabel("Phase [rad]")
ax.set_ylim((0,1))
ax.set_yticks([y for y in np.linspace(0, 1, 11)])
ax.set_ylabel("coefficient")
ax.minorticks_on()
ax.tick_params(which='both', direction='in', color="#3333ee", labelcolor="#000000", zorder=1.8)
ax.grid(True,which='major')
ax.fill( w, window, zorder=2 )
fig.savefig("figure.svg", dpi=300, facecolor='None', edgecolor='None', transparent=True, format="svg")
# pdf,ps,rgba,pgf,svgz,svg,raw,eps,png

f:id:takecccc:20170223005819p:plain

ついでに EMF がほしい場合は Inkscape を使って SVG から変換可能。

d.hatena.ne.jp

for %%A in (%*) do "C:\Program Files\Inkscape\inkscape.exe" -z -f %%A --export-emf %%~dpnA.emf

python内から呼び出す場合は

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import subprocess

N = 256
filename = "figure.svg"
n = np.linspace(0,N,N,False)
#w = 2*np.pi*n/(N-1)
w = 2*np.pi*n/N
# 7 term Blackman-Harris
window = (
        0.27105140069342
        -0.43329793923448*np.cos(w)
        +0.21812299954311*np.cos(2*w)
        -0.06592544638803*np.cos(3*w)
        +0.01081174209837*np.cos(4*w)
        -0.00077658482522*np.cos(5*w)
        +0.00001388721735*np.cos(6*w)
        )

# グラフのサイズを指定(1in=2.54cm)
fig = plt.figure(figsize=(8,2))
ax = fig.gca()
ax.set_xlim((0,2*np.pi))
ax.set_xticks(np.linspace(0, 2*np.pi, 11))
ax.set_xticklabels(["{0:.1f}$\pi$".format(x/np.pi) for x in ax.get_xticks()])
ax.set_xlabel("Phase [rad]")
ax.set_ylim((0,1))
ax.set_yticks([y for y in np.linspace(0, 1, 11)])
ax.set_ylabel("coefficient")
ax.minorticks_on()
ax.tick_params(which='both', direction='in', color="#3333ee", labelcolor="#000000", zorder=1.8)
ax.grid(True,which='major')
ax.fill( w, window, zorder=2 )
fig.savefig(filename, dpi=300, facecolor='None', edgecolor='None', transparent=True)
# pdf,ps,rgba,pgf,svgz,svg,raw,eps,png

subprocess.call('"C:\Program Files\Inkscape\inkscape.exe" -z -f '+filename+' --export-emf '+filename+'.emf', shell=True)