back to thematplotlib-gallery
athttps://github.com/rasbt/matplotlib-gallery
%load_ext watermark
%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
%matplotlib inline
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.
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()
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()
errorbar_default()
errorbar_modified()
data=[np.random.normal(0,std,50)forstdinrange(1,4)]
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()
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()
boxplot_default()
boxplot_modified()
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()
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()
barplot_default()
barplot_modified()
importnumpyasnpimportrandomfrommatplotlibimportpyplotaspltdata1=[random.gauss(15,10)foriinrange(500)]data2=[random.gauss(5,5)foriinrange(500)]
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()
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()
histogram_default()
histogram_modified()
frommatplotlibimportpyplotaspltimportnumpyasnpdefpiechart_default():plt.pie((10,5),labels=('spam','ham'))plt.legend()plt.title('Matplotlib default')plt.show()
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()
piechart_default()
piechart_modified()
importnumpyasnpdata=[np.random.normal(0,std,50)forstdinrange(1,4)]
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()
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()
violin_default()
violin_modified()