Movatterモバイル変換


[0]ホーム

URL:


  1. matplotlib-gallery
  2. ipynb
Notebook

Sebastian Raschka

back to thematplotlib-gallery athttps://github.com/rasbt/matplotlib-gallery

In [1]:
%load_ext watermark
In [2]:
%watermark -u -v -d -p matplotlib,numpy
Last updated: 07/30/2015 CPython 3.4.3IPython 3.2.0matplotlib 1.4.3numpy 1.9.2

In [3]:
%matplotlib inline


Matplotlib Tips and Tricks

Sections







When to use the figure object

[back to top]

Often, we see code that explicitely instantiates a newfigure object:

In [5]:
importmatplotlib.pyplotaspltfig=plt.figure()plt.plot([0,1],[0,1])plt.show()

If we are not planning to manipulate the figure object or add subplots to the figure, this may be redundant. Why? As nicely explained onSO, theplot function retrieves the current figure automatically viagcf ("get current figure") nested inside agca ("get current axes") call. Thus, it really doesn't matter if we create a figure prior toplot unless we are planning to modify it in some way.

In [6]:
importmatplotlib.pyplotaspltplt.plot([0,1],[0,1])plt.show()


Fitting the margins

[back to top]

Although a plot appears perfectly fine inline in a IPython notebook, sometimes we may notice that certain figure elements went missing if we save it to an image file viasavefig. Thetight_layout() function often helps to produce a "tighter" appearence of the plot, it is not sufficient if to fit our graph nicely into the figure boundaries if we plot outside it's margins. Consider the following example:

Typically, this issue can be easily resolved by setting thebbox_inches attribute to'tight' insidesavefig. You can find the complete code example for producing the plot below:

In [1]:
importmatplotlib.pyplotaspltimportnumpyasnp%matplotlib inlinedefgini(p):return(p)*(1-(p))+(1-p)*(1-(1-p))defentropy(p):return-p*np.log2(p)-(1-p)*np.log2((1-p))deferror(p):return1-np.max([p,1-p])x=np.arange(0.0,1.0,0.01)ent=[entropy(p)ifp!=0elseNoneforpinx]sc_ent=[e*0.5ifeelseNoneforeinent]err=[error(i)foriinx]fig=plt.figure()ax=plt.subplot(111)fori,lab,ls,c,inzip([ent,sc_ent,gini(x),err],['Entropy','Entropy (scaled)','Gini Impurity','Misclassification Error'],['-','-','--','-.'],['black','lightgray','red','green','cyan']):line=ax.plot(x,i,label=lab,linestyle=ls,lw=2,color=c)ax.legend(loc='upper center',bbox_to_anchor=(0.5,1.15),ncol=3,fancybox=True,shadow=False)ax.axhline(y=0.5,linewidth=1,color='k',linestyle='--')ax.axhline(y=1.0,linewidth=1,color='k',linestyle='--')plt.ylim([0,1.1])plt.xlabel('p(i=1)')plt.ylabel('Impurity Index')plt.tight_layout()# uncomment the following line to save the image to disk# plt.savefig('./impurity.png', dpi=300, bbox_inches='tight')plt.show()
In [ ]:

[8]ページ先頭

©2009-2025 Movatter.jp