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: 11/08/2014 CPython 3.4.1IPython 2.1.0matplotlib 1.3.1numpy 1.8.1

In [3]:
%matplotlib inline


Formatting I: subplots, markers, colors, axes



Sections



Subplots

[back to top]

In [4]:
importnumpyasnpimportmatplotlib.pyplotaspltx=range(10)y=range(10)fig,ax=plt.subplots(2)forspinax:sp.plot(x,y)


m x n subplots

[back to top]

In [5]:
importmatplotlib.pyplotaspltx=range(10)y=range(10)fig,ax=plt.subplots(nrows=2,ncols=2)forrowinax:forcolinrow:col.plot(x,y)plt.show()
In [6]:
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()


Labeling a subplot grid like a matrix

[back to top]

In [32]:
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()


Shared X- and Y-axes

[back to top]

In [14]:
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()


Setting title and labels

[back to top]

In [20]:
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()


Hiding redundant subplots

[back to top]

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:

In [6]:
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()


Defining colors

[back to top]



3 ways to define colors

[back to top]

Matplotlib supports 3 different ways to encode colors, e.g, if we want to use the color blue, we can define colors as

  • RGB color values (range 0.0 to 1.0) ->(0.0, 0.0, 1.0)
  • matplotlib supported names ->'blue' or'b'
  • HTML hex values ->'#0000FF'
In [18]:
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()


matplotlib color names

[back to top]

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.

In [19]:
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()


Colormaps

[back to top]

More color maps are available athttp://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps

In [4]:
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()


Gray-levels

[back to top]

In [28]:
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()


Edgecolors for scatter plots

[back to top]

In [58]:
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()


Color gradients

[back to top]

In [29]:
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()


Marker styles

[back to top]

In [5]:
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()


Line styles

[back to top]

In [13]:
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()


Fancy and transparent legends

[back to top]

In [8]:
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()


Hiding axes

[back to top]



Hiding axis ticks and labels

[back to top]

In [26]:
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()


Removing frame and ticks

[back to top]

In [29]:
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()


Aesthetic axis layout

[back to top]

In [4]:
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()


Custom tick labels

[back to top]



Text and rotation

[back to top]

In [32]:
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()


Adding a constant value to axis labels

[back to top]

In [7]:
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()




Applying customization and settings globally

[back to top]

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.



Settings for the active session only

[back to top]

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:

In [32]:
importmatplotlibasmplmpl.rcParams['axes.titlesize']='20'

Let's see how it looks like:

In [33]:
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:

In [34]:
mpl.rcdefaults()

Note that we have to re-execute thematplotlib inline magic function afterwards:

In [35]:
%matplotlib inline
In [36]:
plt.plot(x,y)plt.title('default title size')plt.show()


Modifying the matplotlibrc file

[back to top]

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.

In [43]:
importmatplotlibmatplotlib.matplotlib_fname()
Out[43]:
'/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:

In [ ]:
frommatplotlibimportrc_filerc_file('/path/to/matplotlibrc_journalX')importmatplotlib.pyplotasplt

[8]ページ先頭

©2009-2025 Movatter.jp