back to thematplotlib-gallery
athttps://github.com/rasbt/matplotlib-gallery
%load_ext watermark
%watermark -u -v -d -p matplotlib,numpy
Last updated: 11/08/2014 CPython 3.4.1IPython 2.1.0matplotlib 1.3.1numpy 1.8.1
%matplotlib inline
importnumpyasnpimportmatplotlib.pyplotaspltx=range(10)y=range(10)fig,ax=plt.subplots(2)forspinax:sp.plot(x,y)
importmatplotlib.pyplotaspltx=range(10)y=range(10)fig,ax=plt.subplots(nrows=2,ncols=2)forrowinax:forcolinrow:col.plot(x,y)plt.show()
fig,ax=plt.subplots(nrows=2,ncols=2)plt.subplot(2,2,1)plt.plot(x,y)plt.subplot(2,2,2)plt.plot(x,y)plt.subplot(2,2,3)plt.plot(x,y)plt.subplot(2,2,4)plt.plot(x,y)plt.show()
importmatplotlib.pyplotaspltimportnumpyasnpfig,axes=plt.subplots(nrows=3,ncols=3,sharex=True,sharey=True,figsize=(8,8))x=range(5)y=range(5)forrowinaxes:forcolinrow:col.plot(x,y)forax,colinzip(axes[0,:],['1','2','3']):ax.set_title(col,size=20)forax,rowinzip(axes[:,0],['A','B','C']):ax.set_ylabel(row,size=20,rotation=0,labelpad=15)plt.show()
importmatplotlib.pyplotaspltx=range(10)y=range(10)fig,ax=plt.subplots(nrows=2,ncols=2,sharex=True,sharey=True)forrowinax:forcolinrow:col.plot(x,y)plt.show()
importmatplotlib.pyplotaspltx=range(10)y=range(10)fig,ax=plt.subplots(nrows=2,ncols=2)forrowinax:forcolinrow:col.plot(x,y)col.set_title('title')col.set_xlabel('x-axis')col.set_ylabel('x-axis')fig.tight_layout()plt.show()
Sometimes we create more subplots for a rectangular layout (here: 3x3) than we actually need. Here is how we hide those redundant subplots. Let's assume that we only want to show the first 7 subplots:
importmatplotlib.pyplotaspltx=range(10)y=range(10)fig,axes=plt.subplots(nrows=3,ncols=3)forcnt,axinenumerate(axes.ravel()):ifcnt<7:ax.plot(x,y)else:ax.axis('off')# hide subplotplt.show()
Matplotlib supports 3 different ways to encode colors, e.g, if we want to use the color blue, we can define colors as
(0.0, 0.0, 1.0)
'blue'
or'b'
'#0000FF'
importmatplotlib.pyplotaspltsamples=range(1,4)fori,colinzip(samples,[(0.0,0.0,1.0),'blue','#0000FF']):plt.plot([0,10],[0,i],lw=3,color=col)plt.legend(['RGB values: (0.0, 0.0, 1.0)',"matplotlib names: 'blue'","HTML hex values: '#0000FF'"],loc='upper left')plt.title('3 alternatives to define the color blue')plt.show()
The color names that are supported by matplotlib are
b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white
where the first letter represents the shortcut version.
importmatplotlib.pyplotaspltcols=['blue','green','red','cyan','magenta','yellow','black','white']samples=range(1,len(cols)+1)fori,colinzip(samples,cols):plt.plot([0,10],[0,i],label=col,lw=3,color=col)plt.legend(loc='upper left')plt.title('matplotlib color names')plt.show()
More color maps are available athttp://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
importnumpyasnpimportmatplotlib.pyplotaspltfig,(ax0,ax1)=plt.subplots(1,2,figsize=(14,7))samples=range(1,16)# Default Color Cycleforiinsamples:ax0.plot([0,10],[0,i],label=i,lw=3)# Colormapcolormap=plt.cm.Pairedplt.gca().set_color_cycle([colormap(i)foriinnp.linspace(0,0.9,len(samples))])foriinsamples:ax1.plot([0,10],[0,i],label=i,lw=3)# Annotationax0.set_title('Default color cycle')ax1.set_title('plt.cm.Paired colormap')ax0.legend(loc='upper left')ax1.legend(loc='upper left')plt.show()
importmatplotlib.pyplotaspltimportnumpyasnpplt.figure(figsize=(8,6))samples=np.arange(0,1.1,0.1)foriinsamples:plt.plot([0,10],[0,i],label='gray-level%s'%i, lw=3,color=str(i))# ! gray level has to be parsed as stringplt.legend(loc='upper left')plt.title('gray-levels')plt.show()
importmatplotlib.pyplotaspltimportnumpyasnpfig,ax=plt.subplots(nrows=2,ncols=2,figsize=(10,10))samples=np.random.randn(30,2)ax[0][0].scatter(samples[:,0],samples[:,1],color='red',label='color="red"')ax[1][0].scatter(samples[:,0],samples[:,1],c='red',label='c="red"')ax[0][1].scatter(samples[:,0],samples[:,1],edgecolor='white',c='red',label='c="red", edgecolor="white"')ax[1][1].scatter(samples[:,0],samples[:,1],edgecolor='0',c='1',label='color="1.0", edgecolor="0"')forrowinax:forcolinrow:col.legend(loc='upper left')plt.show()
importmatplotlib.pyplotaspltimportmatplotlib.colorsascolimportmatplotlib.cmascmimportnumpyasnp# input datamean_values=np.random.randint(1,101,100)x_pos=range(len(mean_values))fig=plt.figure(figsize=(20,5))# create colormapcmap=cm.ScalarMappable(col.Normalize(min(mean_values),max(mean_values),cm.hot))# plot barsplt.subplot(131)plt.bar(x_pos,mean_values,align='center',alpha=0.5,color=cmap.to_rgba(mean_values))plt.ylim(0,max(mean_values)*1.1)plt.subplot(132)plt.bar(x_pos,np.sort(mean_values),align='center',alpha=0.5,color=cmap.to_rgba(mean_values))plt.ylim(0,max(mean_values)*1.1)plt.subplot(133)plt.bar(x_pos,np.sort(mean_values),align='center',alpha=0.5,color=cmap.to_rgba(np.sort(mean_values)))plt.ylim(0,max(mean_values)*1.1)plt.show()
importmatplotlib.pyplotaspltimportnumpyasnpimportmatplotlib.pyplotaspltmarkers=['.',# point',',# pixel'o',# circle'v',# triangle down'^',# triangle up'<',# triangle_left'>',# triangle_right'1',# tri_down'2',# tri_up'3',# tri_left'4',# tri_right'8',# octagon's',# square'p',# pentagon'*',# star'h',# hexagon1'H',# hexagon2'+',# plus'x',# x'D',# diamond'd',# thin_diamond'|',# vline]plt.figure(figsize=(13,10))samples=range(len(markers))foriinsamples:plt.plot([i-1,i,i+1],[i,i,i],label=markers[i],marker=markers[i],markersize=10)# Annotationplt.title('Matplotlib Marker styles',fontsize=20)plt.ylim([-1,len(markers)+1])plt.legend(loc='lower right')plt.show()
importnumpyasnpimportmatplotlib.pyplotaspltlinestyles=['-.','--','None','-',':']plt.figure(figsize=(8,5))samples=range(len(linestyles))foriinsamples:plt.plot([i-1,i,i+1],[i,i,i],label='"%s"'%linestyles[i],linestyle=linestyles[i],lw=4)# Annotationplt.title('Matplotlib line styles',fontsize=20)plt.ylim([-1,len(linestyles)+1])plt.legend(loc='lower right')plt.show()
importnumpyasnpimportmatplotlib.pyplotaspltX1=np.random.randn(100,2)X2=np.random.randn(100,2)X3=np.random.randn(100,2)R1=(X1**2).sum(axis=1)R2=(X2**2).sum(axis=1)R3=(X3**2).sum(axis=1)plt.scatter(X1[:,0],X1[:,1],c='blue',marker='o',s=32.*R1,edgecolor='black',label='Dataset X1',alpha=0.7)plt.scatter(X2[:,0],X2[:,1],c='gray',marker='s',s=32.*R2,edgecolor='black',label='Dataset X2',alpha=0.7)plt.scatter(X2[:,0],X3[:,1],c='green',marker='^',s=32.*R3,edgecolor='black',label='Dataset X3',alpha=0.7)plt.xlim([-3,3])plt.ylim([-3,3])leg=plt.legend(loc='upper left',fancybox=True)leg.get_frame().set_alpha(0.5)plt.show()
importnumpyasnpimportmatplotlib.pyplotaspltx=range(10)y=range(10)fig=plt.gca()plt.plot(x,y)fig.axes.get_xaxis().set_visible(False)fig.axes.get_yaxis().set_visible(False)plt.show()
importnumpyasnpimportmatplotlib.pyplotaspltx=range(10)y=range(10)fig=plt.gca()plt.plot(x,y)# removing framefig.spines["top"].set_visible(False)fig.spines["bottom"].set_visible(False)fig.spines["right"].set_visible(False)fig.spines["left"].set_visible(False)# removing ticksplt.tick_params(axis="both",which="both",bottom="off",top="off",labelbottom="on",left="off",right="off",labelleft="on")plt.show()
importnumpyasnpimportmathimportmatplotlib.pyplotaspltX=np.random.normal(loc=0.0,scale=1.0,size=300)width=0.5bins=np.arange(math.floor(X.min())-width,math.ceil(X.max())+width,width)# fixed bin sizeax=plt.subplot(111)# remove axis at the top and to the rightax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)# hide axis ticksplt.tick_params(axis="both",which="both",bottom="off",top="off",labelbottom="on",left="off",right="off",labelleft="on")plt.hist(X,alpha=0.5,bins=bins)plt.grid()plt.xlabel('x label')plt.ylabel('y label')plt.title('title')plt.show()
importmatplotlib.pyplotaspltx=range(10)y=range(10)labels=['super long axis label'foriinrange(10)]fig,ax=plt.subplots()plt.plot(x,y)# set custom tick labelsax.set_xticklabels(labels,rotation=45,horizontalalignment='right')plt.show()
importmatplotlib.pyplotaspltCONST=10x=range(10)y=range(10)labels=[i+CONSTforiinx]fig,ax=plt.subplots()plt.plot(x,y)plt.xlabel('x-value + 10')# set custom tick labelsax.set_xticklabels(labels)plt.show()
Everyone has a different perception of "style", and usually, we would make some little adjustments to matplotlib's default visuals here and there. After customization, it would be tedious to repeat the same code over and over again every time we produce a new plot.
However we have multiple options to apply the changes globally.
Here, we are only interested in the settings for the current session. In this case, one way to customize matplotlibs defaults would be the 'rcParams' attribute (in the next session, you will see a handy reference for all the different matplotlib settings). E.g., if we want to make the font size of our titles larger for all plots that follow in the active session, we could type the following:
importmatplotlibasmplmpl.rcParams['axes.titlesize']='20'
Let's see how it looks like:
frommatplotlibimportpyplotaspltx=range(10)y=range(10)plt.plot(x,y)plt.title('larger title')plt.show()
And if we want to revert it back to the default settings, we can use the command:
mpl.rcdefaults()
Note that we have to re-execute thematplotlib inline
magic function afterwards:
%matplotlib inline
plt.plot(x,y)plt.title('default title size')plt.show()
Let's assume that we decided to always prefer a particular setting over matplotlib's default (e.g., a larger font size for the title like in the previous section), we can make a change to thematplotlibrc
file: This way we'd avoid to change the setting every time we start a new session or produce a new plot.
Thematplotlibrc
file can reside in different places depending on your sytem. An convenient way to find out the location is to use thematplotlib_fname()
function.
importmatplotlibmatplotlib.matplotlib_fname()
'/Users/sebastian/miniconda3/envs/py34/lib/python3.4/site-packages/matplotlib/mpl-data/matplotlibrc'
If we open this file in an editor, we will see an overview of all the different matplotlib default settings and their default values. We can use this list either as a reference to apply changes dynamically (see the previous section), or we can un-comment this line here and change its default value. E.g., we want to change the title size again, we could change the following line:
axes.titlesize : 20
One thing to keep in mind is that this file becomes overwritten if we install a new version of matplotlib, and it is always recommended to keep backups as you change the settings (the file with its original default settings can be foundhere).
Sometimes, we even want to keep and use multiplematplotlibrc
files, e.g., if we are writing articles for different journals and every journal has its own requirement for figure formats.In this case, we can load our ownrc
files from a different local directory:
frommatplotlibimportrc_filerc_file('/path/to/matplotlibrc_journalX')importmatplotlib.pyplotasplt