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,scipy
Last updated: 09/10/2014 CPython 3.4.1IPython 2.2.0matplotlib 1.4.0numpy 1.9.0scipy 0.14.0

In [3]:
%matplotlib inline

Preparing Plots for Publication via matplotlib

Sometimes, we are not quite happy with matplotlib's default designs. Here are a few suggestions to adjust matplotlib's default plots so that they are more pleasing in the viewer's eye.

In this section, I will re-use certain settings for different types of plots, but if you'd like to change the settings globally (for the active session or even in the matplotlib settings) please see the sectionApplying customization and settings globally.

Sections



Errorbar Plots

[back to top]



Default Errorbar Plot

In [4]:
importmatplotlib.pyplotaspltdeferrorbar_default():# Datadata=[1,1.5,1.2]std_devs=[0.15,0.25,0.12]# X axis positionsx_pos=range(len(data))ford,std,xinzip(data,std_devs,x_pos):plt.errorbar(x=x,y=d,yerr=std,fmt='o')# setting axis limitsplt.xlim([min(x_pos)-1,max(x_pos)+1])plt.ylim([min(data)*0.7,max(data)*1.3])# setting labels and titlesplt.ylabel('x label')plt.title('Matplotlib default')plt.legend(['X1','X2','X3'],loc='upper right')plt.show()

Modified Errorbar Plot

In [7]:
importnumpyasnpdeferrorbar_modified():# Datadata=[1,1.5,1.2]std_devs=[0.15,0.25,0.12]# X axis positionsx_pos=range(len(data))colors=['lightblue','pink','lightgreen']fig=plt.gca()ax=plt.subplot(111)# draw plotsford,std,col,xinzip(data,std_devs,colors,x_pos):plt.errorbar(x=x,y=d,yerr=std,fmt='o',color=col,ecolor='black')# setting axis limitsplt.xlim([min(x_pos)-1,max(x_pos)+1])plt.ylim([min(data)*0.7,max(data)*1.3])# setting labels and titlesplt.ylabel('x label')plt.text(1,2,'Modified',horizontalalignment='center',fontsize=14)# remove axis spinesax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)ax.spines["bottom"].set_visible(False)ax.spines["left"].set_visible(False)# hiding axis ticksplt.tick_params(axis="both",which="both",bottom="off",top="off",labelbottom="off",left="off",right="off",labelleft="on")# adding horizontal grid linesax.yaxis.grid(True)plt.legend(['X1','X2','X3'],loc='upper right',fancybox=True,numpoints=1)plt.tight_layout()plt.show()
In [8]:
errorbar_default()

In [9]:
errorbar_modified()


Boxplots

[back to top]

In [11]:
data=[np.random.normal(0,std,50)forstdinrange(1,4)]

Default Boxplot

In [12]:
importmatplotlib.pyplotaspltimportnumpyasnpdefboxplot_default():fig=plt.figure(figsize=(8,6))plt.boxplot(data,notch=False,# box instead of notch shapesym='rs',# red squares for outliersvert=True)# vertical box aligmnentplt.xticks([y+1foryinrange(len(data))],['x1','x2','x3'])plt.title('Matplotlib default')plt.show()

Modified Boxplot

In [23]:
defboxplot_modified():fig=plt.figure(figsize=(8,6))ax=plt.subplot(111)bplot=plt.boxplot(data,notch=True,# notch shapevert=True,# vertical box aligmnentsym='ko',# red circle for outlierspatch_artist=True,# fill with color)# choosing custom colors to fill the boxescolors=['pink','lightblue','lightgreen']forpatch,colorinzip(bplot['boxes'],colors):patch.set_facecolor(color)# modifying the whiskers: straight lines, black, widerforwhiskerinbplot['whiskers']:whisker.set(color='black',linewidth=1.2,linestyle='-')# making the caps a little bit widerforcapinbplot['caps']:cap.set(linewidth=1.2)# hiding axis ticksplt.tick_params(axis="both",which="both",bottom="off",top="off",labelbottom="on",left="off",right="off",labelleft="on")# adding horizontal grid linesax.yaxis.grid(True)# remove axis spinesax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)ax.spines["bottom"].set_visible(False)ax.spines["left"].set_visible(False)plt.xticks([y+1foryinrange(len(data))],['x1','x2','x3'])# raised titleplt.text(2,9,'Modified',horizontalalignment='center',fontsize=18)plt.tight_layout()plt.show()
In [24]:
boxplot_default()

In [25]:
boxplot_modified()


Barplots



[back to top]

Default Barplot

In [26]:
importmatplotlib.pyplotaspltdefbarplot_default():# input datamean_values=[1,2,3]variance=[0.2,0.4,0.5]bar_labels=['bar 1','bar 2','bar 3']fig=plt.figure(figsize=(6,4))# plot barsx_pos=list(range(len(bar_labels)))plt.bar(x_pos,mean_values,yerr=variance,align='center')# set axes labels and titleplt.ylabel('variable y')plt.xticks(x_pos,bar_labels)plt.title('Matplotlib default')plt.show()

Modified Barplot

In [30]:
importmatplotlib.pyplotaspltdefbarplot_modified():# input datamean_values=[1,2,3]variance=[0.2,0.4,0.5]bar_labels=['bar 1','bar 2','bar 3']fig=plt.figure(figsize=(6,4))ax=plt.subplot(111)# plot barsx_pos=list(range(len(bar_labels)))plt.bar(x_pos,mean_values,yerr=variance,ecolor='black',# black error bar coloralpha=0.5,# transparencywidth=0.5,# smaller bar widthalign='center')# set height of the y-axismax_y=max(zip(mean_values,variance))# returns a tuple, here: (3, 5)plt.ylim([0,(max_y[0]+max_y[1])*1.1])# hiding axis ticksplt.tick_params(axis="both",which="both",bottom="off",top="off",labelbottom="on",left="off",right="off",labelleft="on")# adding horizontal grid linesax.yaxis.grid(True)# remove axis spinesax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)ax.spines["bottom"].set_visible(False)ax.spines["left"].set_visible(False)# set axes labels and titleplt.ylabel('variable y')plt.xticks(x_pos,bar_labels)plt.text(1,4,'Modified',horizontalalignment='center',fontsize=18)plt.tight_layout()plt.show()
In [31]:
barplot_default()

In [32]:
barplot_modified()


Histograms

[back to top]

In [33]:
importnumpyasnpimportrandomfrommatplotlibimportpyplotaspltdata1=[random.gauss(15,10)foriinrange(500)]data2=[random.gauss(5,5)foriinrange(500)]

Default Histogram

In [34]:
defhistogram_default():fig=plt.figure(figsize=(8,6))bins=np.arange(-60,60,2.5)# plot histogramsplt.hist(data1,bins=bins,label='class 1')plt.hist(data2,bins=bins,label='class 2')# labelsplt.title('Matplotlib default')plt.xlabel('variable X')plt.ylabel('count')plt.legend(loc='upper right')plt.show()

Modified Histogram

In [40]:
defhistogram_modified():bins=np.arange(-60,60,2.5)fig=plt.figure(figsize=(8,6))ax=plt.subplot(111)# plot histogramsplt.hist(data1,bins=bins,alpha=0.3,# transparencylabel='class 1')plt.hist(data2,bins=bins,alpha=0.3,# transparencylabel='class 2')# axis formattingplt.ylim([0,110])plt.xlim([min(data1+data2)-5,max(data1+data2)+5])# hiding axis ticksplt.tick_params(axis="both",which="both",bottom="off",top="off",labelbottom="on",left="off",right="off",labelleft="on")# adding horizontal grid linesax.yaxis.grid(True)# remove axis spinesax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)ax.spines["bottom"].set_visible(False)ax.spines["left"].set_visible(False)# labelsplt.xlabel('variable X')plt.ylabel('count')plt.legend(loc='upper right',fancybox=True)# raised titleplt.text(15,120,'Modified',horizontalalignment='center',fontsize=18)plt.show()
In [41]:
histogram_default()

In [42]:
histogram_modified()


Pie charts

[back to top]

Default pie chart

In [8]:
frommatplotlibimportpyplotaspltimportnumpyasnpdefpiechart_default():plt.pie((10,5),labels=('spam','ham'))plt.legend()plt.title('Matplotlib default')plt.show()

Modified pie chart

In [9]:
defpiechart_modified():plt.pie((10,5),labels=('spam','ham'),shadow=True,colors=('lightskyblue','yellowgreen'),explode=(0,0.15),# space between slicesstartangle=90,# rotate conter-clockwise by 90 degreesautopct='%1.1f%%',# display fraction as percentage)plt.legend(fancybox=True)plt.axis('equal')# plot pyplot as circleplt.tight_layout()plt.title('Modified')plt.show()
In [10]:
piechart_default()
In [11]:
piechart_modified()


Violin plots

[back to top]

In [5]:
importnumpyasnpdata=[np.random.normal(0,std,50)forstdinrange(1,4)]

Default violin plot

In [10]:
importmatplotlib.pyplotaspltdefviolin_default():fig=plt.figure(figsize=(8,6))plt.violinplot(data)plt.xticks([y+1foryinrange(len(data))],['x1','x2','x3'])plt.title('Matplotlib default')plt.show()

Modified violin plot

In [14]:
defviolin_modified():fig=plt.figure(figsize=(8,6))ax=plt.subplot(111)vplot=plt.violinplot(data,showmeans=False,showmedians=True,showextrema=False)# choosing custom colors to fill the boxescolors=['red','blue','green']forpatch,colorinzip(vplot['bodies'],colors):patch.set_facecolor(color)# hiding axis ticksplt.tick_params(axis="both",which="both",bottom="off",top="off",labelbottom="on",left="off",right="off",labelleft="on")# adding horizontal grid linesax.yaxis.grid(True)# remove axis spinesax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)ax.spines["bottom"].set_visible(False)ax.spines["left"].set_visible(False)plt.xticks([y+1foryinrange(len(data))],['x1','x2','x3'])# raised titleplt.text(2,9,'Modified',horizontalalignment='center',fontsize=18)plt.tight_layout()plt.show()
In [15]:
violin_default()
In [16]:
violin_modified()

[8]ページ先頭

©2009-2025 Movatter.jp