Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Matplotlib tutorial for beginner

NotificationsYou must be signed in to change notification settings

kevintogit/matplotlib-tutorial

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nicolas P. Rougier

Sources are available fromgithub

All code and material is licensed under aCreative CommonsAttribution-ShareAlike 4.0.

You can test your installation before the tutorial using thecheck-installation.py script.

See also:

matplotlib is probably the single most used Python package for 2D-graphics. Itprovides both a very quick way to visualize data from Python andpublication-quality figures in many formats. We are going to explorematplotlib in interactive mode covering most common cases.

IPython and the pylab mode

IPython is an enhanced interactive Python shell thathas lots of interesting features including named inputs and outputs, access toshell commands, improved debugging and much more. When we start it with thecommand line argument -pylab (--pylab since IPython version 0.12), it allowsinteractive matplotlib sessions that have Matlab/Mathematica-like functionality.

pyplot

pyplot provides a convenient interface to the matplotlib object-orientedplotting library. It is modeled closely after Matlab(TM). Therefore, themajority of plotting commands in pyplot have Matlab(TM) analogs with similararguments. Important commands are explained with interactive examples.

In this section, we want to draw the cosine and sine functions on the sameplot. Starting from the default settings, we'll enrich the figure step by stepto make it nicer.

The first step is to get the data for the sine and cosine functions:

import numpy as npX = np.linspace(-np.pi, np.pi, 256, endpoint=True)C, S = np.cos(X), np.sin(X)

X is now a NumPy array with 256 values ranging from -π to +π (included). C isthe cosine (256 values) and S is the sine (256 values).

To run the example, you can download each of the examples and run it using:

$ python exercice_1.py

You can get source for each step by clicking on the corresponding figure.

Using defaults

figures/exercice_1.png

Matplotlib comes with a set of default settings that allow customizing allkinds of properties. You can control the defaults of almost every property inmatplotlib: figure size and dpi, line width, color and style, axes, axis andgrid properties, text and font properties and so on. While matplotlib defaultsare rather good in most cases, you may want to modify some properties forspecific cases.

Instantiating defaults

figures/exercice_2.png

In the script below, we've instantiated (and commented) all the figure settingsthat influence the appearance of the plot. The settings have been explicitlyset to their default values, but now you can interactively play with the valuesto explore their affect (seeLine properties andLine styles below).

Changing colors and line widths

figures/exercice_3.png

As a first step, we want to have the cosine in blue and the sine in red and aslightly thicker line for both of them. We'll also slightly alter the figuresize to make it more horizontal.

...plt.figure(figsize=(10,6), dpi=80)plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-")...

Setting limits

figures/exercice_4.png

Current limits of the figure are a bit too tight and we want to make some spacein order to clearly see all data points.

...plt.xlim(X.min()*1.1, X.max()*1.1)plt.ylim(C.min()*1.1, C.max()*1.1)...

Setting ticks

figures/exercice_5.png

Current ticks are not ideal because they do not show the interesting values(+/-π,+/-π/2) for sine and cosine. We'll change them such that they show onlythese values.

...plt.xticks( [-np.pi, -np.pi/2, 0, np.pi/2, np.pi])plt.yticks([-1, 0, +1])...

Setting tick labels

figures/exercice_6.png

Ticks are now properly placed but their label is not very explicit. We couldguess that 3.142 is π but it would be better to make it explicit. When we settick values, we can also provide a corresponding label in the second argumentlist. Note that we'll use latex to allow for nice rendering of the label.

...plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],       [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])plt.yticks([-1, 0, +1],       [r'$-1$', r'$0$', r'$+1$'])...

Moving spines

figures/exercice_7.png

Spines are the lines connecting the axis tick marks and noting the boundariesof the data area. They can be placed at arbitrary positions and until now, theywere on the border of the axis. We'll change that since we want to have them inthe middle. Since there are four of them (top/bottom/left/right), we'll discardthe top and right by setting their color to none and we'll move the bottom andleft ones to coordinate 0 in data space coordinates.

...ax = plt.gca()ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))...

Adding a legend

figures/exercice_8.png

Let's add a legend in the upper left corner. This only requires adding thekeyword argument label (that will be used in the legend box) to the plotcommands.

...plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-", label="sine")plt.legend(loc='upper left', frameon=False)...

Annotate some points

figures/exercice_9.png

Let's annotate some interesting points using the annotate command. We choose the2π/3 value and we want to annotate both the sine and the cosine. We'll firstdraw a marker on the curve as well as a straight dotted line. Then, we'll usethe annotate command to display some text with an arrow.

...t = 2*np.pi/3plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=1.5, linestyle="--")plt.scatter([t,],[np.cos(t),], 50, color ='blue')plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',             xy=(t, np.sin(t)), xycoords='data',             xytext=(+10, +30), textcoords='offset points', fontsize=16,             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=1.5, linestyle="--")plt.scatter([t,],[np.sin(t),], 50, color ='red')plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',             xy=(t, np.cos(t)), xycoords='data',             xytext=(-90, -50), textcoords='offset points', fontsize=16,             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))...

Devil is in the details

Documentation

figures/exercice_10.png

The tick labels are now hardly visible because of the blue and red lines. We canmake them bigger and we can also adjust their properties such that they'll berendered on a semi-transparent white background. This will allow us to see boththe data and the labels.

...for label in ax.get_xticklabels() + ax.get_yticklabels():    label.set_fontsize(16)    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 ))...

So far we have used implicit figure and axes creation. This is handy for fastplots. We can have more control over the display using figure, subplot, andaxes explicitly. A figure in matplotlib means the whole window in the userinterface. Within this figure there can be subplots. While subplot positionsthe plots in a regular grid, axes allows free placement within the figure. Bothcan be useful depending on your intention. We've already worked with figuresand subplots without explicitly calling them. When we call plot, matplotlibcalls gca() to get the current axes and gca in turn calls gcf() to get thecurrent figure. If there is none it calls figure() to make one, strictlyspeaking, to make a subplot(111). Let's look at the details.

Figures

A figure is the windows in the GUI that has "Figure #" as title. Figuresare numbered starting from 1 as opposed to the normal Python way startingfrom 0. This is clearly MATLAB-style. There are several parameters thatdetermine what the figure looks like:

ArgumentDefaultDescription
num1number of figure
figsizefigure.figsizefigure size in in inches (width, height)
dpifigure.dpiresolution in dots per inch
facecolorfigure.facecolorcolor of the drawing background
edgecolorfigure.edgecolorcolor of edge around the drawing background
frameonTruedraw figure frame or not

The defaults can be specified in the resource file and will be used most of thetime. Only the number of the figure is frequently changed.

When you work with the GUI you can close a figure by clicking on the x in theupper right corner. You can also close a figure programmatically by callingclose. Depending on the argument it closes (1) the current figure (noargument), (2) a specific figure (figure number or figure instance asargument), or (3) all figures (all as argument).

As with other objects, you can set figure properties with the set_something methods.

Subplots

With subplot you can arrange plots in a regular grid. You need to specify thenumber of rows and columns and the number of the plot. Note that thegridspec command is a morepowerful alternative.

figures/subplot-horizontal.pngfigures/subplot-vertical.pngfigures/subplot-grid.pngfigures/gridspec.png

Axes

Axes are very similar to subplots but allow placement of plots at any locationin the figure. So if we want to put a smaller plot inside a bigger one we doso with axes.

figures/axes.pngfigures/axes-2.png

Ticks

Well formatted ticks are an important part of publishing-readyfigures. Matplotlib provides a totally configurable system for ticks. There aretick locators to specify where ticks should appear and tick formatters to giveticks the appearance you want. Major and minor ticks can be located andformatted independently from each other. By default minor ticks are not shown,i.e. there is only an empty list for them because it is as NullLocator (seebelow).

Tick Locators

There are several locators for different kind of requirements:

ClassDescription
NullLocator

No ticks.

figures/ticks-NullLocator.png
IndexLocator

Place a tick on every multiple of some base number of points plotted.

figures/ticks-IndexLocator.png
FixedLocator

Tick locations are fixed.

figures/ticks-FixedLocator.png
LinearLocator

Determine the tick locations.

figures/ticks-LinearLocator.png
MultipleLocator

Set a tick on every integer that is multiple of some base.

figures/ticks-MultipleLocator.png
AutoLocator

Select no more than n intervals at nice locations.

figures/ticks-AutoLocator.png
LogLocator

Determine the tick locations for log axes.

figures/ticks-LogLocator.png

All of these locators derive from the base class matplotlib.ticker.Locator.You can make your own locator deriving from it. Handling dates as ticks can beespecially tricky. Therefore, matplotlib provides special locators inmatplotlib.dates.

For quite a long time, animation in matplotlib was not an easy task and wasdone mainly through clever hacks. However, things have started to change sinceversion 1.1 and the introduction of tools for creating animation veryintuitively, with the possibility to save them in all kind of formats (but don'texpect to be able to run very complex animations at 60 fps though).

Documentation

The most easy way to make an animation in matplotlib is to declare aFuncAnimation object that specifies to matplotlib what is the figure toupdate, what is the update function and what is the delay between frames.

Drip drop

A very simple rain effect can be obtained by having small growing ringsrandomly positioned over a figure. Of course, they won't grow forever since thewave is supposed to damp with time. To simulate that, we can use a more andmore transparent color as the ring is growing, up to the point where it is nomore visible. At this point, we remove the ring and create a new one.

First step is to create a blank figure:

# New figure with white backgroundfig=plt.figure(figsize=(6,6),facecolor='white')# New axis over the whole figure, no frame and a 1:1 aspect ratioax=fig.add_axes([0,0,1,1],frameon=False,aspect=1)

Next, we need to create several rings. For this, we can use the scatter plotobject that is generally used to visualize points cloud, but we can also use itto draw rings by specifying we don't have a facecolor. We also have to takecare of initial size and color for each ring such that we have all sizes betweena minimum and a maximum size. In addition, we need to make sure the largest ringis almost transparent.

figures/rain-static.png
# Number of ringn=50size_min=50size_max=50*50# Ring positionP=np.random.uniform(0,1,(n,2))# Ring colorsC=np.ones((n,4))* (0,0,0,1)# Alpha color channel goes from 0 (transparent) to 1 (opaque)C[:,3]=np.linspace(0,1,n)# Ring sizesS=np.linspace(size_min,size_max,n)# Scatter plotscat=ax.scatter(P[:,0],P[:,1],s=S,lw=0.5,edgecolors=C,facecolors='None')# Ensure limits are [0,1] and remove ticksax.set_xlim(0,1),ax.set_xticks([])ax.set_ylim(0,1),ax.set_yticks([])

Now, we need to write the update function for our animation. We know that ateach time step each ring should grow and become more transparent while thelargest ring should be totally transparent and thus removed. Of course, we won'tactually remove the largest ring but re-use it to set a new ring at a new randomposition, with nominal size and color. Hence, we keep the number of ringsconstant.

figures/rain.gif
defupdate(frame):globalP,C,S# Every ring is made more transparentC[:,3]=np.maximum(0,C[:,3]-1.0/n)# Each ring is made largerS+= (size_max-size_min)/n# Reset ring specific ring (relative to frame number)i=frame%50P[i]=np.random.uniform(0,1,2)S[i]=size_minC[i,3]=1# Update scatter objectscat.set_edgecolors(C)scat.set_sizes(S)scat.set_offsets(P)# Return the modified objectreturnscat,

Last step is to tell matplotlib to use this function as an update function forthe animation and display the result or save it as a movie:

animation=FuncAnimation(fig,update,interval=10,blit=True,frames=200)# animation.save('rain.gif', writer='imagemagick', fps=30, dpi=40)plt.show()

Earthquakes

We'll now use the rain animation to visualize earthquakes on the planet fromthe last 30 days. The USGS Earthquake Hazards Program is part of the NationalEarthquake Hazards Reduction Program (NEHRP) and provides several data on theirwebsite. Those data are sorted according toearthquakes magnitude, ranging from significant only down to all earthquakes,major or minor. You would be surprised by the number of minor earthquakeshappening every hour on the planet. Since this would represent too much datafor us, we'll stick to earthquakes with magnitude > 4.5. At the time of writing,this already represent more than 300 earthquakes in the last 30 days.

First step is to read and convert data. We'll use the urllib library thatallows us to open and read remote data. Data on the website use the CSV formatwhose content is given by the first line:

time,latitude,longitude,depth,mag,magType,nst,gap,dmin,rms,net,id,updated,place,type2015-08-17T13:49:17.320Z,37.8365,-122.2321667,4.82,4.01,mw,...2015-08-15T07:47:06.640Z,-10.9045,163.8766,6.35,6.6,mwp,...

We are only interested in latitude, longitude and magnitude and we won't parsetime of event (ok, that's bad, feel free to send me a PR).

importurllibfrommpl_toolkits.basemapimportBasemap# -> http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.phpfeed="http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/"# Significant earthquakes in the last 30 days# url = urllib.request.urlopen(feed + "significant_month.csv")# Magnitude > 4.5url=urllib.request.urlopen(feed+"4.5_month.csv")# Magnitude > 2.5# url = urllib.request.urlopen(feed + "2.5_month.csv")# Magnitude > 1.0# url = urllib.request.urlopen(feed + "1.0_month.csv")# Reading and storage of datadata=url.read()data=data.split(b'\n')[+1:-1]E=np.zeros(len(data),dtype=[('position',float,2),                               ('magnitude',float,1)])foriinrange(len(data)):row=data[i].split(',')E['position'][i]=float(row[2]),float(row[1])E['magnitude'][i]=float(row[4])

Now, we need to draw the earth on a figure to show precisely where the earthquakecenter is and to translate latitude/longitude in some coordinates matplotlibcan handle. Fortunately, there is thebasemap project (that tends to be replaced by themore completecartopy) that is reallysimple to install and to use. First step is to define a projection to draw theearth onto a screen (there exists many different projections) and we'll stickto the mill projection which is rather standard for non-specialist like me.

fig=plt.figure(figsize=(14,10))ax=plt.subplot(1,1,1)earth=Basemap(projection='mill')

Next, we request to draw coastline and fill continents:

earth.drawcoastlines(color='0.50',linewidth=0.25)earth.fillcontinents(color='0.95')

The earth object will also be used to translate coordinates quiteautomatically. We are almost finished. Last step is to adapt the rain code andput some eye candy:

P=np.zeros(50,dtype=[('position',float,2),                         ('size',float,1),                         ('growth',float,1),                         ('color',float,4)])scat=ax.scatter(P['position'][:,0],P['position'][:,1],P['size'],lw=0.5,edgecolors=P['color'],facecolors='None',zorder=10)defupdate(frame):current=frame%len(E)i=frame%len(P)P['color'][:,3]=np.maximum(0,P['color'][:,3]-1.0/len(P))P['size']+=P['growth']magnitude=E['magnitude'][current]P['position'][i]=earth(*E['position'][current])P['size'][i]=5P['growth'][i]=np.exp(magnitude)*0.1ifmagnitude<6:P['color'][i]=0,0,1,1else:P['color'][i]=1,0,0,1scat.set_edgecolors(P['color'])scat.set_facecolors(P['color']*(1,1,1,0.25))scat.set_sizes(P['size'])scat.set_offsets(P['position'])returnscat,animation=FuncAnimation(fig,update,interval=10)plt.show()

If everything went well, you should obtain something like this (with animation):

figures/earthquakes.pngfigures/plot.pngfigures/scatter.pngfigures/bar.pngfigures/contour.pngfigures/imshow.pngfigures/quiver.pngfigures/pie.pngfigures/grid.pngfigures/multiplot.pngfigures/polar.pngfigures/plot3d.pngfigures/text.png

Regular Plots

figures/plot_ex.png

Hints

You need to use thefill_betweencommand.

Starting from the code below, try to reproduce the graphic on the right takingcare of filled areas.

import numpy as npimport matplotlib.pyplot as pltn = 256X = np.linspace(-np.pi,np.pi,n,endpoint=True)Y = np.sin(2*X)plt.plot (X, Y+1, color='blue', alpha=1.00)plt.plot (X, Y-1, color='blue', alpha=1.00)plt.show()

Click on figure for solution.

Scatter Plots

figures/scatter_ex.png

Hints

Color is given by angle of (X,Y).

Starting from the code below, try to reproduce the graphic on the right takingcare of marker size, color and transparency.

import numpy as npimport matplotlib.pyplot as pltn = 1024X = np.random.normal(0,1,n)Y = np.random.normal(0,1,n)plt.scatter(X,Y)plt.show()

Click on figure for solution.

Bar Plots

figures/bar_ex.png

Hints

You need to take care of text alignment.

Starting from the code below, try to reproduce the graphic on the right byadding labels for red bars.

import numpy as npimport matplotlib.pyplot as pltn = 12X = np.arange(n)Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')for x,y in zip(X,Y1):    plt.text(x+0.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom')plt.ylim(-1.25,+1.25)plt.show()

Click on figure for solution.

Contour Plots

figures/contour_ex.png

Hints

You need to use theclabelcommand.

Starting from the code below, try to reproduce the graphic on the right takingcare of the colormap (seeColormaps below).

import numpy as npimport matplotlib.pyplot as pltdef f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)n = 256x = np.linspace(-3,3,n)y = np.linspace(-3,3,n)X,Y = np.meshgrid(x,y)plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap='jet')C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)plt.show()

Click on figure for solution.

Imshow

figures/imshow_ex.png

Hints

You need to take care of theorigin of the image in the imshow command anduse acolorbar.

Starting from the code below, try to reproduce the graphic on the right takingcare of colormap, image interpolation and origin.

import numpy as npimport matplotlib.pyplot as pltdef f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)n = 10x = np.linspace(-3,3,4*n)y = np.linspace(-3,3,3*n)X,Y = np.meshgrid(x,y)plt.imshow(f(X,Y))plt.show()

Click on figure for solution.

Pie Charts

figures/pie_ex.png

Hints

You need to modify Z.

Starting from the code below, try to reproduce the graphic on the right takingcare of colors and slices size.

import numpy as npimport matplotlib.pyplot as pltn = 20Z = np.random.uniform(0,1,n)plt.pie(Z)plt.show()

Click on figure for solution.

Quiver Plots

figures/quiver_ex.png

Hints

You need to draw arrows twice.

Starting from the code above, try to reproduce the graphic on the right takingcare of colors and orientations.

import numpy as npimport matplotlib.pyplot as pltn = 8X,Y = np.mgrid[0:n,0:n]plt.quiver(X,Y)plt.show()

Click on figure for solution.

Grids

figures/grid_ex.png

Starting from the code below, try to reproduce the graphic on the right takingcare of line styles.

import numpy as npimport matplotlib.pyplot as pltaxes = gca()axes.set_xlim(0,4)axes.set_ylim(0,3)axes.set_xticklabels([])axes.set_yticklabels([])plt.show()

Click on figure for solution.

Multi Plots

figures/multiplot_ex.png

Hints

You can use several subplots with different partition.

Starting from the code below, try to reproduce the graphic on the right.

import numpy as npimport matplotlib.pyplot as pltplt.subplot(2,2,1)plt.subplot(2,2,3)plt.subplot(2,2,4)plt.show()

Click on figure for solution.

Polar Axis

figures/polar_ex.png

Hints

You only need to modify theaxes line.

Starting from the code below, try to reproduce the graphic on the right.

import numpy as npimport matplotlib.pyplot as pltplt.axes([0,0,1,1])N = 20theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)radii = 10*np.random.rand(N)width = np.pi/4*np.random.rand(N)bars = plt.bar(theta, radii, width=width, bottom=0.0)for r,bar in zip(radii, bars):    bar.set_facecolor( cm.jet(r/10.))    bar.set_alpha(0.5)plt.show()

Click on figure for solution.

3D Plots

figures/plot3d_ex.png

Hints

You need to usecontourf.

Starting from the code below, try to reproduce the graphic on the right.

import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure()ax = Axes3D(fig)X = np.arange(-4, 4, 0.25)Y = np.arange(-4, 4, 0.25)X, Y = np.meshgrid(X, Y)R = np.sqrt(X**2 + Y**2)Z = np.sin(R)ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')plt.show()

Click on figure for solution.

Text

figures/text_ex.png

Hints

Have a look at thematplotlib logo.

Try to do the same from scratch!

Click on figure for solution.

Matplotlib benefits from extensive documentation as well as a largecommunity of users and developpers. Here are some links of interest:

Tutorials

  • Pyplot tutorial
    • Introduction
    • Controlling line properties
    • Working with multiple figures and axes
    • Working with text
  • Image tutorial
    • Startup commands
    • Importing image data into Numpy arrays
    • Plotting numpy arrays as images
  • Text tutorial
    • Text introduction
    • Basic text commands
    • Text properties and layout
    • Writing mathematical expressions
    • Text rendering With LaTeX
    • Annotating text
  • Artist tutorial
    • Introduction
    • Customizing your objects
    • Object containers
    • Figure container
    • Axes container
    • Axis containers
    • Tick containers
  • Path tutorial
    • Introduction
    • Bézier example
    • Compound paths
  • Transforms tutorial
    • Introduction
    • Data coordinates
    • Axes coordinates
    • Blended transformations
    • Using offset transforms to create a shadow effect
    • The transformation pipeline

Matplotlib documentation

Code documentation

The code is fairly well documented and you can quickly access a specificcommand from within a python session:

>>> from pylab import *>>> help(plot)Help on function plot in module matplotlib.pyplot:plot(*args, **kwargs)   Plot lines and/or markers to the   :class:`~matplotlib.axes.Axes`.  *args* is a variable length   argument, allowing for multiple *x*, *y* pairs with an   optional format string.  For example, each of the following is   legal::       plot(x, y)         # plot x and y using default line style and color       plot(x, y, 'bo')   # plot x and y using blue circle markers       plot(y)            # plot y using x as index array 0..N-1       plot(y, 'r+')      # ditto, but with red plusses   If *x* and/or *y* is 2-dimensional, then the corresponding columns   will be plotted.   ...

Galleries

Thematplotlib gallery isalso incredibly useful when you search how to render a given graphic. Eachexample comes with its source.

A smaller gallery is also availablehere.

Mailing lists

Finally, there is auser mailing list where you canask for help and adevelopers mailing list that is moretechnical.

Here is a set of tables that show main properties and styles.

Line properties

PropertyDescriptionAppearance
alpha (or a)alpha transparency on 0-1 scalefigures/alpha.png
antialiasedTrue or False - use antialised renderingfigures/aliased.pngfigures/antialiased.png
color (or c)matplotlib color argfigures/color.png
linestyle (or ls)seeLine properties 
linewidth (or lw)float, the line width in pointsfigures/linewidth.png
solid_capstyleCap style for solid linesfigures/solid_capstyle.png
solid_joinstyleJoin style for solid linesfigures/solid_joinstyle.png
dash_capstyleCap style for dashesfigures/dash_capstyle.png
dash_joinstyleJoin style for dashesfigures/dash_joinstyle.png
markerseeMarkers 
markeredgewidth (mew)line width around the marker symbolfigures/mew.png
markeredgecolor (mec)edge color if a marker is usedfigures/mec.png
markerfacecolor (mfc)face color if a marker is usedfigures/mfc.png
markersize (ms)size of the marker in pointsfigures/ms.png

Line styles

SymbolDescriptionAppearance
-solid linefigures/linestyle--.png
--dashed linefigures/linestyle---.png
-.dash-dot linefigures/linestyle--dot.png
:dotted linefigures/linestyle-:.png
.pointsfigures/linestyle-dot.png
,pixelsfigures/linestyle-,.png
ocirclefigures/linestyle-o.png
^triangle upfigures/linestyle-^.png
vtriangle downfigures/linestyle-v.png
<triangle leftfigures/linestyle-<.png
>triangle rightfigures/linestyle->.png
ssquarefigures/linestyle-s.png
+plusfigures/linestyle-+.png
xcrossfigures/linestyle-x.png
Ddiamondfigures/linestyle-dd.png
dthin diamondfigures/linestyle-d.png
1tripod downfigures/linestyle-1.png
2tripod upfigures/linestyle-2.png
3tripod leftfigures/linestyle-3.png
4tripod rightfigures/linestyle-4.png
hhexagonfigures/linestyle-h.png
Hrotated hexagonfigures/linestyle-hh.png
ppentagonfigures/linestyle-p.png
|vertical linefigures/linestyle-|.png
_horizontal linefigures/linestyle-_.png

Markers

SymbolDescriptionAppearance
0tick leftfigures/marker-i0.png
1tick rightfigures/marker-i1.png
2tick upfigures/marker-i2.png
3tick downfigures/marker-i3.png
4caret leftfigures/marker-i4.png
5caret rightfigures/marker-i5.png
6caret upfigures/marker-i6.png
7caret downfigures/marker-i7.png
ocirclefigures/marker-o.png
Ddiamondfigures/marker-dd.png
hhexagon 1figures/marker-h.png
Hhexagon 2figures/marker-hh.png
_horizontal linefigures/marker-_.png
1tripod downfigures/marker-1.png
2tripod upfigures/marker-2.png
3tripod leftfigures/marker-3.png
4tripod rightfigures/marker-4.png
8octagonfigures/marker-8.png
ppentagonfigures/marker-p.png
^triangle upfigures/marker-^.png
vtriangle downfigures/marker-v.png
<triangle leftfigures/marker-<.png
>triangle rightfigures/marker->.png
dthin diamondfigures/marker-d.png
,pixelfigures/marker-,.png
+plusfigures/marker-+.png
.pointfigures/marker-dot.png
ssquarefigures/marker-s.png
*starfigures/marker-*.png
|vertical linefigures/marker-|.png
xcrossfigures/marker-x.png
r'$\sqrt{2}$'any latex expressionfigures/marker-latex.png

Colormaps

All colormaps can be reversed by appending_r. For instance,gray_r isthe reverse ofgray.

If you want to know more about colormaps, seeDocumenting the matplotlibcolormaps.

Base

NameAppearance
autumnfigures/cmap-autumn.png
bonefigures/cmap-bone.png
coolfigures/cmap-cool.png
copperfigures/cmap-copper.png
flagfigures/cmap-flag.png
grayfigures/cmap-gray.png
hotfigures/cmap-hot.png
hsvfigures/cmap-hsv.png
jetfigures/cmap-jet.png
pinkfigures/cmap-pink.png
prismfigures/cmap-prism.png
spectralfigures/cmap-spectral.png
springfigures/cmap-spring.png
summerfigures/cmap-summer.png
winterfigures/cmap-winter.png

GIST

NameAppearance
gist_earthfigures/cmap-gist_earth.png
gist_grayfigures/cmap-gist_gray.png
gist_heatfigures/cmap-gist_heat.png
gist_ncarfigures/cmap-gist_ncar.png
gist_rainbowfigures/cmap-gist_rainbow.png
gist_sternfigures/cmap-gist_stern.png
gist_yargfigures/cmap-gist_yarg.png

Sequential

NameAppearance
BrBGfigures/cmap-BrBG.png
PiYGfigures/cmap-PiYG.png
PRGnfigures/cmap-PRGn.png
PuOrfigures/cmap-PuOr.png
RdBufigures/cmap-RdBu.png
RdGyfigures/cmap-RdGy.png
RdYlBufigures/cmap-RdYlBu.png
RdYlGnfigures/cmap-RdYlGn.png
Spectralfigures/cmap-spectral-2.png

Diverging

NameAppearance
Bluesfigures/cmap-Blues.png
BuGnfigures/cmap-BuGn.png
BuPufigures/cmap-BuPu.png
GnBufigures/cmap-GnBu.png
Greensfigures/cmap-Greens.png
Greysfigures/cmap-Greys.png
Orangesfigures/cmap-Oranges.png
OrRdfigures/cmap-OrRd.png
PuBufigures/cmap-PuBu.png
PuBuGnfigures/cmap-PuBuGn.png
PuRdfigures/cmap-PuRd.png
Purplesfigures/cmap-Purples.png
RdPufigures/cmap-RdPu.png
Redsfigures/cmap-Reds.png
YlGnfigures/cmap-YlGn.png
YlGnBufigures/cmap-YlGnBu.png
YlOrBrfigures/cmap-YlOrBr.png
YlOrRdfigures/cmap-YlOrRd.png

Qualitative

NameAppearance
Accentfigures/cmap-Accent.png
Dark2figures/cmap-Dark2.png
Pairedfigures/cmap-Paired.png
Pastel1figures/cmap-Pastel1.png
Pastel2figures/cmap-Pastel2.png
Set1figures/cmap-Set1.png
Set2figures/cmap-Set2.png
Set3figures/cmap-Set3.png

Miscellaneous

NameAppearance
afmhotfigures/cmap-afmhot.png
binaryfigures/cmap-binary.png
brgfigures/cmap-brg.png
bwrfigures/cmap-bwr.png
coolwarmfigures/cmap-coolwarm.png
CMRmapfigures/cmap-CMRmap.png
cubehelixfigures/cmap-cubehelix.png
gnuplotfigures/cmap-gnuplot.png
gnuplot2figures/cmap-gnuplot2.png
oceanfigures/cmap-ocean.png
rainbowfigures/cmap-rainbow.png
seismicfigures/cmap-seismic.png
terrainfigures/cmap-terrain.png

About

Matplotlib tutorial for beginner

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python82.7%
  • CSS16.0%
  • Makefile1.3%

[8]ページ先頭

©2009-2025 Movatter.jp