2017-02-05 3 views
1

私は2Dプロットをカスタマイズしました。今後のプロットで軸、ラベル、フォントサイズなどの設定を再利用したいと思います。例えば、私は、この特定のプロットのための次の設定を設定した、と私は何とか将来図における使用のための「スタイル」として保存できるようにしたいと思います。特に将来のプロットでカスタム図の設定を使用

import matplotlib.pyplot as plt 
import numpy as np 

x = np.linspace(-2, 2) 
y = x**2 

fig, ax = plt.subplots() 

# text specific to this plot, but attributes common to all 
ax.plot(x, y, label='$y = x^2$', linewidth=2) 
ax.set_xlabel('$x$', fontsize=20) 
ax.set_ylabel('$y$', fontsize=20) 
ax.set_title('Graph of $y = x^2$', fontsize=20) 

# common to all plots 
ax.legend(loc='best') 
ax.spines['bottom'].set_color('grey') 
ax.spines['left'].set_color('grey') 
ax.xaxis.label.set_color('grey') 
ax.yaxis.label.set_color('grey') 
ax.spines['top'].set_visible(False) 
ax.spines['right'].set_visible(False) 
ax.yaxis.set_ticks_position('left') 
ax.xaxis.set_ticks_position('bottom') 
ax.tick_params(colors='grey') 

plt.show() 

、用関数内の文字列はこの図に固有のものですが、linewidth=2のような属性は将来の図を共有したいと思います。 # common to all plotsの下の行は、すべての将来の数字を共有したいと思う属性です。 plt.figure()の引数として、使いやすさのためにこれを「スタイル」として保存する方法はありますか?

答えて

1

Matplotlibでは、プロットの設定の多くについて、あらかじめ定義されたパラメータの意味でスタイルを使用することができます。

matplotlib customization articleには、優れた紹介とサンプルが掲載されています。

独自のスタイルファイルを作成することもできます。 matplotlibディレクトリは、print matplotlib.get_configdir()で見つけることができるスタイルファイルを探します。このフォルダに、stylelibというサブフォルダが作成されていない場合は作成します。 mystyle.mplstyleというファイルを作成します。 あなたのケースでは、このファイルの内容は、あなたが今、エントリmystyleを見つける必要がありますあなたはprint plt.style.available経由で入手リストで

### MATPLOTLIBRC FORMAT 
lines.linewidth : 2  # line width in points 
axes.edgecolor  : grey # axes edge color 
axes.titlesize  : 20 # fontsize of the axes title 
axes.labelsize  : 20 # fontsize of the x any y labels 
axes.labelcolor  : grey 
axes.spines.left : True # display axis spines 
axes.spines.bottom : True 
axes.spines.top : False 
axes.spines.right : False 
xtick.top   : False # draw ticks on the top side 
xtick.bottom   : True # draw ticks on the bottom side 
xtick.color   : grey  # color of the tick labels 
ytick.left   : True # draw ticks on the left side 
ytick.right   : False # draw ticks on the right side 
ytick.color   : grey  # color of the tick labels 
legend.loc   : best 

だろう。 あなたのpythonスクリプトはplt.style.use('mystyle')でこのスタイルを読むことができます。 そして、あなたのプロットスクリプトは、まだ伝説を得ることがax.legend()を呼び出す必要が

import matplotlib.pyplot as plt 

plt.style.use('mystyle') 

fig, ax = plt.subplots() 
x=range(8) 
y=[1,5,4,3,2,7,4,5] 

ax.plot(x, y, label='$y = x^2$') 
ax.set_xlabel('$x$') 
ax.set_ylabel('$y$') 
ax.set_title('Graph of $y = x^2$') 
ax.legend() 

plt.show() 

ノートに減少させることができます。

何かが期待どおりに機能しない場合は、特定の細かい質問をしてください。

+0

@ImportanceoOfBeingErnest大きな謝辞をありがとう。唯一の問題は、上軸と右軸のティックがまだ表示されていることです。どのようにこれらを取り除くためにどのようなアイデア? – bcf

+0

私はmatplotlib 2.0でそれをテストし、うまくいきました。どのバージョンを使用していますか?あなたは私の答えからスニペットを正確にコピーしましたか?見た目のイメージを表示できますか(おそらくimgur.comなどにアップロードしてください)? – ImportanceOfBeingErnest

+0

私はmatplotlibを2.0.0にアップグレードしました。再度、感謝します! – bcf

関連する問題