matplotlib & pandas

This commit is contained in:
estomm
2020-09-26 22:03:11 +08:00
parent 73cc328c81
commit d31be4f219
599 changed files with 99925 additions and 0 deletions

View File

@@ -0,0 +1,794 @@
---
sidebarDepth: 3
sidebar: auto
---
# Customizing Matplotlib with style sheets and rcParams
Tips for customizing the properties and default styles of Matplotlib.
## Using style sheets
The ``style`` package adds support for easy-to-switch plotting "styles" with
the same parameters as a
[matplotlib rc](#customizing-with-matplotlibrc-files) file (which is read
at startup to configure matplotlib).
There are a number of pre-defined styles [provided by Matplotlib](https://github.com/matplotlib/matplotlib/tree/master/lib/matplotlib/mpl-data/stylelib). For
example, there's a pre-defined style called "ggplot", which emulates the
aesthetics of [ggplot](https://ggplot2.tidyverse.org/) (a popular plotting package for [R](https://www.r-project.org/)). To use this style,
just add:
``` python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('ggplot')
data = np.random.randn(50)
```
To list all available styles, use:
``` python
print(plt.style.available)
```
Out:
```
['seaborn-dark', 'dark_background', 'seaborn-pastel', 'seaborn-colorblind', 'tableau-colorblind10', 'seaborn-notebook', 'seaborn-dark-palette', 'grayscale', 'seaborn-poster', 'seaborn', 'bmh', 'seaborn-talk', 'seaborn-ticks', '_classic_test', 'ggplot', 'seaborn-white', 'classic', 'Solarize_Light2', 'seaborn-paper', 'fast', 'fivethirtyeight', 'seaborn-muted', 'seaborn-whitegrid', 'seaborn-darkgrid', 'seaborn-bright', 'seaborn-deep']
```
## Defining your own style
You can create custom styles and use them by calling ``style.use`` with the
path or URL to the style sheet. Additionally, if you add your
``.mplstyle`` file to ``mpl_configdir/stylelib``, you can reuse
your custom style sheet with a call to ``style.use()``. By default
``mpl_configdir`` should be ``~/.config/matplotlib``, but you can check where
yours is with ``matplotlib.get_configdir()``; you may need to create this
directory. You also can change the directory where matplotlib looks for
the stylelib/ folder by setting the MPLCONFIGDIR environment variable,
see [matplotlib configuration and cache directory locations](https://matplotlib.orgfaq/troubleshooting_faq.html#locating-matplotlib-config-dir).
Note that a custom style sheet in ``mpl_configdir/stylelib`` will
override a style sheet defined by matplotlib if the styles have the same name.
For example, you might want to create
``mpl_configdir/stylelib/presentation.mplstyle`` with the following:
``` python
axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16
```
Then, when you want to adapt a plot designed for a paper to one that looks
good in a presentation, you can just add:
``` python
>>> import matplotlib.pyplot as plt
>>> plt.style.use('presentation')
```
## Composing styles
Style sheets are designed to be composed together. So you can have a style
sheet that customizes colors and a separate style sheet that alters element
sizes for presentations. These styles can easily be combined by passing
a list of styles:
``` python
>>> import matplotlib.pyplot as plt
>>> plt.style.use(['dark_background', 'presentation'])
```
Note that styles further to the right will overwrite values that are already
defined by styles on the left.
## Temporary styling
If you only want to use a style for a specific block of code but don't want
to change the global styling, the style package provides a context manager
for limiting your changes to a specific scope. To isolate your styling
changes, you can write something like the following:
``` python
with plt.style.context('dark_background'):
plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
plt.show()
```
![sphx_glr_customizing_001](https://matplotlib.org/_images/sphx_glr_customizing_001.png)
# matplotlib rcParams
## Dynamic rc settings
You can also dynamically change the default rc settings in a python script or
interactively from the python shell. All of the rc settings are stored in a
dictionary-like variable called [``matplotlib.rcParams``](https://matplotlib.orgapi/matplotlib_configuration_api.html#matplotlib.rcParams), which is global to
the matplotlib package. rcParams can be modified directly, for example:
``` python
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'
plt.plot(data)
```
![sphx_glr_customizing_002](https://matplotlib.org/_images/sphx_glr_customizing_002.png)
Matplotlib also provides a couple of convenience functions for modifying rc
settings. The [``matplotlib.rc()``](https://matplotlib.orgapi/matplotlib_configuration_api.html#matplotlib.rc) command can be used to modify multiple
settings in a single group at once, using keyword arguments:
``` python
mpl.rc('lines', linewidth=4, color='g')
plt.plot(data)
```
![sphx_glr_customizing_003](https://matplotlib.org/_images/sphx_glr_customizing_003.png)
The [``matplotlib.rcdefaults()``](https://matplotlib.orgapi/matplotlib_configuration_api.html#matplotlib.rcdefaults) command will restore the standard matplotlib
default settings.
There is some degree of validation when setting the values of rcParams, see
[``matplotlib.rcsetup``](https://matplotlib.orgapi/rcsetup_api.html#module-matplotlib.rcsetup) for details.
## The ``matplotlibrc`` file
matplotlib uses ``matplotlibrc`` configuration files to customize all kinds
of properties, which we call ``rc settings`` or ``rc parameters``. You can control
the defaults of almost every property in matplotlib: figure size and dpi, line
width, color and style, axes, axis and grid properties, text and font
properties and so on. matplotlib looks for ``matplotlibrc`` in four
locations, in the following order:
Once a ``matplotlibrc`` file has been found, it will *not* search any of
the other paths.
To display where the currently active ``matplotlibrc`` file was
loaded from, one can do the following:
``` python
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/home/foo/.config/matplotlib/matplotlibrc'
```
See below for a sample [matplotlibrc file](#matplotlibrc-sample).
### A sample matplotlibrc file
``` python
#### MATPLOTLIBRC FORMAT
## This is a sample matplotlib configuration file - you can find a copy
## of it on your system in
## site-packages/matplotlib/mpl-data/matplotlibrc. If you edit it
## there, please note that it will be overwritten in your next install.
## If you want to keep a permanent local copy that will not be
## overwritten, place it in the following location:
## unix/linux:
## $HOME/.config/matplotlib/matplotlibrc or
## $XDG_CONFIG_HOME/matplotlib/matplotlibrc (if $XDG_CONFIG_HOME is set)
## other platforms:
## $HOME/.matplotlib/matplotlibrc
##
## See http://matplotlib.org/users/customizing.html#the-matplotlibrc-file for
## more details on the paths which are checked for the configuration file.
##
## This file is best viewed in a editor which supports python mode
## syntax highlighting. Blank lines, or lines starting with a comment
## symbol, are ignored, as are trailing comments. Other lines must
## have the format
## key : val ## optional comment
##
## Colors: for the color values below, you can either use - a
## matplotlib color string, such as r, k, or b - an rgb tuple, such as
## (1.0, 0.5, 0.0) - a hex string, such as ff00ff - a scalar
## grayscale intensity such as 0.75 - a legal html color name, e.g., red,
## blue, darkslategray
##### CONFIGURATION BEGINS HERE
## The default backend. If you omit this parameter, the first
## working backend from the following list is used:
## MacOSX Qt5Agg Qt4Agg Gtk3Agg TkAgg WxAgg Agg
##
## Other choices include:
## Qt5Cairo Qt4Cairo GTK3Cairo TkCairo WxCairo Cairo Wx PS PDF SVG Template.
##
## You can also deploy your own backend outside of matplotlib by
## referring to the module name (which must be in the PYTHONPATH) as
## 'module://my_backend'.
#backend : Agg
## Note that this can be overridden by the environment variable
## QT_API used by Enthought Tool Suite (ETS); valid values are
## "pyqt" and "pyside". The "pyqt" setting has the side effect of
## forcing the use of Version 2 API for QString and QVariant.
## The port to use for the web server in the WebAgg backend.
#webagg.port : 8988
## The address on which the WebAgg web server should be reachable
#webagg.address : 127.0.0.1
## If webagg.port is unavailable, a number of other random ports will
## be tried until one that is available is found.
#webagg.port_retries : 50
## When True, open the webbrowser to the plot that is shown
#webagg.open_in_browser : True
## if you are running pyplot inside a GUI and your backend choice
## conflicts, we will automatically try to find a compatible one for
## you if backend_fallback is True
#backend_fallback: True
#interactive : False
#toolbar : toolbar2 ## None | toolbar2 ("classic" is deprecated)
#timezone : UTC ## a pytz timezone string, e.g., US/Central or Europe/Paris
## Where your matplotlib data lives if you installed to a non-default
## location. This is where the matplotlib fonts, bitmaps, etc reside
#datapath : /home/jdhunter/mpldata
#### LINES
## See http://matplotlib.org/api/artist_api.html#module-matplotlib.lines for more
## information on line properties.
#lines.linewidth : 1.5 ## line width in points
#lines.linestyle : - ## solid line
#lines.color : C0 ## has no affect on plot(); see axes.prop_cycle
#lines.marker : None ## the default marker
#lines.markerfacecolor : auto ## the default markerfacecolor
#lines.markeredgecolor : auto ## the default markeredgecolor
#lines.markeredgewidth : 1.0 ## the line width around the marker symbol
#lines.markersize : 6 ## markersize, in points
#lines.dash_joinstyle : round ## miter|round|bevel
#lines.dash_capstyle : butt ## butt|round|projecting
#lines.solid_joinstyle : round ## miter|round|bevel
#lines.solid_capstyle : projecting ## butt|round|projecting
#lines.antialiased : True ## render lines in antialiased (no jaggies)
## The three standard dash patterns. These are scaled by the linewidth.
#lines.dashed_pattern : 3.7, 1.6
#lines.dashdot_pattern : 6.4, 1.6, 1, 1.6
#lines.dotted_pattern : 1, 1.65
#lines.scale_dashes : True
#markers.fillstyle: full ## full|left|right|bottom|top|none
#### PATCHES
## Patches are graphical objects that fill 2D space, like polygons or
## circles. See
## http://matplotlib.org/api/artist_api.html#module-matplotlib.patches
## information on patch properties
#patch.linewidth : 1 ## edge width in points.
#patch.facecolor : C0
#patch.edgecolor : black ## if forced, or patch is not filled
#patch.force_edgecolor : False ## True to always use edgecolor
#patch.antialiased : True ## render patches in antialiased (no jaggies)
#### HATCHES
#hatch.color : black
#hatch.linewidth : 1.0
#### Boxplot
#boxplot.notch : False
#boxplot.vertical : True
#boxplot.whiskers : 1.5
#boxplot.bootstrap : None
#boxplot.patchartist : False
#boxplot.showmeans : False
#boxplot.showcaps : True
#boxplot.showbox : True
#boxplot.showfliers : True
#boxplot.meanline : False
#boxplot.flierprops.color : black
#boxplot.flierprops.marker : o
#boxplot.flierprops.markerfacecolor : none
#boxplot.flierprops.markeredgecolor : black
#boxplot.flierprops.markeredgewidth : 1.0
#boxplot.flierprops.markersize : 6
#boxplot.flierprops.linestyle : none
#boxplot.flierprops.linewidth : 1.0
#boxplot.boxprops.color : black
#boxplot.boxprops.linewidth : 1.0
#boxplot.boxprops.linestyle : -
#boxplot.whiskerprops.color : black
#boxplot.whiskerprops.linewidth : 1.0
#boxplot.whiskerprops.linestyle : -
#boxplot.capprops.color : black
#boxplot.capprops.linewidth : 1.0
#boxplot.capprops.linestyle : -
#boxplot.medianprops.color : C1
#boxplot.medianprops.linewidth : 1.0
#boxplot.medianprops.linestyle : -
#boxplot.meanprops.color : C2
#boxplot.meanprops.marker : ^
#boxplot.meanprops.markerfacecolor : C2
#boxplot.meanprops.markeredgecolor : C2
#boxplot.meanprops.markersize : 6
#boxplot.meanprops.linestyle : --
#boxplot.meanprops.linewidth : 1.0
#### FONT
## font properties used by text.Text. See
## http://matplotlib.org/api/font_manager_api.html for more
## information on font properties. The 6 font properties used for font
## matching are given below with their default values.
##
## The font.family property has five values: 'serif' (e.g., Times),
## 'sans-serif' (e.g., Helvetica), 'cursive' (e.g., Zapf-Chancery),
## 'fantasy' (e.g., Western), and 'monospace' (e.g., Courier). Each of
## these font families has a default list of font names in decreasing
## order of priority associated with them. When text.usetex is False,
## font.family may also be one or more concrete font names.
##
## The font.style property has three values: normal (or roman), italic
## or oblique. The oblique style will be used for italic, if it is not
## present.
##
## The font.variant property has two values: normal or small-caps. For
## TrueType fonts, which are scalable fonts, small-caps is equivalent
## to using a font size of 'smaller', or about 83%% of the current font
## size.
##
## The font.weight property has effectively 13 values: normal, bold,
## bolder, lighter, 100, 200, 300, ..., 900. Normal is the same as
## 400, and bold is 700. bolder and lighter are relative values with
## respect to the current weight.
##
## The font.stretch property has 11 values: ultra-condensed,
## extra-condensed, condensed, semi-condensed, normal, semi-expanded,
## expanded, extra-expanded, ultra-expanded, wider, and narrower. This
## property is not currently implemented.
##
## The font.size property is the default font size for text, given in pts.
## 10 pt is the standard value.
#font.family : sans-serif
#font.style : normal
#font.variant : normal
#font.weight : normal
#font.stretch : normal
## note that font.size controls default text sizes. To configure
## special text sizes tick labels, axes, labels, title, etc, see the rc
## settings for axes and ticks. Special text sizes can be defined
## relative to font.size, using the following values: xx-small, x-small,
## small, medium, large, x-large, xx-large, larger, or smaller
#font.size : 10.0
#font.serif : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif : DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive : Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive
#font.fantasy : Comic Sans MS, Chicago, Charcoal, ImpactWestern, Humor Sans, xkcd, fantasy
#font.monospace : DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
#### TEXT
## text properties used by text.Text. See
## http://matplotlib.org/api/artist_api.html#module-matplotlib.text for more
## information on text properties
#text.color : black
#### LaTeX customizations. See http://wiki.scipy.org/Cookbook/Matplotlib/UsingTex
#text.usetex : False ## use latex for all text handling. The following fonts
## are supported through the usual rc parameter settings:
## new century schoolbook, bookman, times, palatino,
## zapf chancery, charter, serif, sans-serif, helvetica,
## avant garde, courier, monospace, computer modern roman,
## computer modern sans serif, computer modern typewriter
## If another font is desired which can loaded using the
## LaTeX \usepackage command, please inquire at the
## matplotlib mailing list
#text.latex.preamble : ## IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES
## AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP
## IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO.
## text.latex.preamble is a single line of LaTeX code that
## will be passed on to the LaTeX system. It may contain
## any code that is valid for the LaTeX "preamble", i.e.
## between the "\documentclass" and "\begin{document}"
## statements.
## Note that it has to be put on a single line, which may
## become quite long.
## The following packages are always loaded with usetex, so
## beware of package collisions: color, geometry, graphicx,
## type1cm, textcomp.
## Adobe Postscript (PSSNFS) font packages may also be
## loaded, depending on your font settings.
#text.latex.preview : False
#text.hinting : auto ## May be one of the following:
## none: Perform no hinting
## auto: Use FreeType's autohinter
## native: Use the hinting information in the
# font file, if available, and if your
# FreeType library supports it
## either: Use the native hinting information,
# or the autohinter if none is available.
## For backward compatibility, this value may also be
## True === 'auto' or False === 'none'.
#text.hinting_factor : 8 ## Specifies the amount of softness for hinting in the
## horizontal direction. A value of 1 will hint to full
## pixels. A value of 2 will hint to half pixels etc.
#text.antialiased : True ## If True (default), the text will be antialiased.
## This only affects the Agg backend.
## The following settings allow you to select the fonts in math mode.
## They map from a TeX font name to a fontconfig font pattern.
## These settings are only used if mathtext.fontset is 'custom'.
## Note that this "custom" mode is unsupported and may go away in the
## future.
#mathtext.cal : cursive
#mathtext.rm : sans
#mathtext.tt : monospace
#mathtext.it : sans:italic
#mathtext.bf : sans:bold
#mathtext.sf : sans
#mathtext.fontset : dejavusans ## Should be 'dejavusans' (default),
## 'dejavuserif', 'cm' (Computer Modern), 'stix',
## 'stixsans' or 'custom'
#mathtext.fallback_to_cm : True ## When True, use symbols from the Computer Modern
## fonts when a symbol can not be found in one of
## the custom math fonts.
#mathtext.default : it ## The default font to use for math.
## Can be any of the LaTeX font names, including
## the special name "regular" for the same font
## used in regular text.
#### AXES
## default face and edge color, default tick sizes,
## default fontsizes for ticklabels, and so on. See
## http://matplotlib.org/api/axes_api.html#module-matplotlib.axes
#axes.facecolor : white ## axes background color
#axes.edgecolor : black ## axes edge color
#axes.linewidth : 0.8 ## edge linewidth
#axes.grid : False ## display grid or not
#axes.grid.axis : both ## which axis the grid should apply to
#axes.grid.which : major ## gridlines at major, minor or both ticks
#axes.titlesize : large ## fontsize of the axes title
#axes.titleweight : normal ## font weight of title
#axes.titlepad : 6.0 ## pad between axes and title in points
#axes.labelsize : medium ## fontsize of the x any y labels
#axes.labelpad : 4.0 ## space between label and axis
#axes.labelweight : normal ## weight of the x and y labels
#axes.labelcolor : black
#axes.axisbelow : line ## draw axis gridlines and ticks below
## patches (True); above patches but below
## lines ('line'); or above all (False)
#axes.formatter.limits : -7, 7 ## use scientific notation if log10
## of the axis range is smaller than the
## first or larger than the second
#axes.formatter.use_locale : False ## When True, format tick labels
## according to the user's locale.
## For example, use ',' as a decimal
## separator in the fr_FR locale.
#axes.formatter.use_mathtext : False ## When True, use mathtext for scientific
## notation.
#axes.formatter.min_exponent: 0 ## minimum exponent to format in scientific notation
#axes.formatter.useoffset : True ## If True, the tick label formatter
## will default to labeling ticks relative
## to an offset when the data range is
## small compared to the minimum absolute
## value of the data.
#axes.formatter.offset_threshold : 4 ## When useoffset is True, the offset
## will be used when it can remove
## at least this number of significant
## digits from tick labels.
#axes.spines.left : True ## display axis spines
#axes.spines.bottom : True
#axes.spines.top : True
#axes.spines.right : True
#axes.unicode_minus : True ## use unicode for the minus symbol
## rather than hyphen. See
## http://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
#axes.prop_cycle : cycler('color', ['1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf'])
## color cycle for plot lines as list of string
## colorspecs: single letter, long name, or web-style hex
## Note the use of string escapes here ('1f77b4', instead of 1f77b4)
## as opposed to the rest of this file.
#axes.autolimit_mode : data ## How to scale axes limits to the data.
## Use "data" to use data limits, plus some margin
## Use "round_number" move to the nearest "round" number
#axes.xmargin : .05 ## x margin. See `axes.Axes.margins`
#axes.ymargin : .05 ## y margin See `axes.Axes.margins`
#polaraxes.grid : True ## display grid on polar axes
#axes3d.grid : True ## display grid on 3d axes
#### DATES
## These control the default format strings used in AutoDateFormatter.
## Any valid format datetime format string can be used (see the python
## `datetime` for details). For example using '%%x' will use the locale date representation
## '%%X' will use the locale time representation and '%%c' will use the full locale datetime
## representation.
## These values map to the scales:
## {'year': 365, 'month': 30, 'day': 1, 'hour': 1/24, 'minute': 1 / (24 * 60)}
#date.autoformatter.year : %Y
#date.autoformatter.month : %Y-%m
#date.autoformatter.day : %Y-%m-%d
#date.autoformatter.hour : %m-%d %H
#date.autoformatter.minute : %d %H:%M
#date.autoformatter.second : %H:%M:%S
#date.autoformatter.microsecond : %M:%S.%f
#### TICKS
## see http://matplotlib.org/api/axis_api.html#matplotlib.axis.Tick
#xtick.top : False ## draw ticks on the top side
#xtick.bottom : True ## draw ticks on the bottom side
#xtick.labeltop : False ## draw label on the top
#xtick.labelbottom : True ## draw label on the bottom
#xtick.major.size : 3.5 ## major tick size in points
#xtick.minor.size : 2 ## minor tick size in points
#xtick.major.width : 0.8 ## major tick width in points
#xtick.minor.width : 0.6 ## minor tick width in points
#xtick.major.pad : 3.5 ## distance to major tick label in points
#xtick.minor.pad : 3.4 ## distance to the minor tick label in points
#xtick.color : black ## color of the tick labels
#xtick.labelsize : medium ## fontsize of the tick labels
#xtick.direction : out ## direction: in, out, or inout
#xtick.minor.visible : False ## visibility of minor ticks on x-axis
#xtick.major.top : True ## draw x axis top major ticks
#xtick.major.bottom : True ## draw x axis bottom major ticks
#xtick.minor.top : True ## draw x axis top minor ticks
#xtick.minor.bottom : True ## draw x axis bottom minor ticks
#xtick.alignment : center ## alignment of xticks
#ytick.left : True ## draw ticks on the left side
#ytick.right : False ## draw ticks on the right side
#ytick.labelleft : True ## draw tick labels on the left side
#ytick.labelright : False ## draw tick labels on the right side
#ytick.major.size : 3.5 ## major tick size in points
#ytick.minor.size : 2 ## minor tick size in points
#ytick.major.width : 0.8 ## major tick width in points
#ytick.minor.width : 0.6 ## minor tick width in points
#ytick.major.pad : 3.5 ## distance to major tick label in points
#ytick.minor.pad : 3.4 ## distance to the minor tick label in points
#ytick.color : black ## color of the tick labels
#ytick.labelsize : medium ## fontsize of the tick labels
#ytick.direction : out ## direction: in, out, or inout
#ytick.minor.visible : False ## visibility of minor ticks on y-axis
#ytick.major.left : True ## draw y axis left major ticks
#ytick.major.right : True ## draw y axis right major ticks
#ytick.minor.left : True ## draw y axis left minor ticks
#ytick.minor.right : True ## draw y axis right minor ticks
#ytick.alignment : center_baseline ## alignment of yticks
#### GRIDS
#grid.color : b0b0b0 ## grid color
#grid.linestyle : - ## solid
#grid.linewidth : 0.8 ## in points
#grid.alpha : 1.0 ## transparency, between 0.0 and 1.0
#### Legend
#legend.loc : best
#legend.frameon : True ## if True, draw the legend on a background patch
#legend.framealpha : 0.8 ## legend patch transparency
#legend.facecolor : inherit ## inherit from axes.facecolor; or color spec
#legend.edgecolor : 0.8 ## background patch boundary color
#legend.fancybox : True ## if True, use a rounded box for the
## legend background, else a rectangle
#legend.shadow : False ## if True, give background a shadow effect
#legend.numpoints : 1 ## the number of marker points in the legend line
#legend.scatterpoints : 1 ## number of scatter points
#legend.markerscale : 1.0 ## the relative size of legend markers vs. original
#legend.fontsize : medium
#legend.title_fontsize : None ## None sets to the same as the default axes.
## Dimensions as fraction of fontsize:
#legend.borderpad : 0.4 ## border whitespace
#legend.labelspacing : 0.5 ## the vertical space between the legend entries
#legend.handlelength : 2.0 ## the length of the legend lines
#legend.handleheight : 0.7 ## the height of the legend handle
#legend.handletextpad : 0.8 ## the space between the legend line and legend text
#legend.borderaxespad : 0.5 ## the border between the axes and legend edge
#legend.columnspacing : 2.0 ## column separation
#### FIGURE
## See http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure
#figure.titlesize : large ## size of the figure title (Figure.suptitle())
#figure.titleweight : normal ## weight of the figure title
#figure.figsize : 6.4, 4.8 ## figure size in inches
#figure.dpi : 100 ## figure dots per inch
#figure.facecolor : white ## figure facecolor
#figure.edgecolor : white ## figure edgecolor
#figure.frameon : True ## enable figure frame
#figure.max_open_warning : 20 ## The maximum number of figures to open through
## the pyplot interface before emitting a warning.
## If less than one this feature is disabled.
## The figure subplot parameters. All dimensions are a fraction of the
#figure.subplot.left : 0.125 ## the left side of the subplots of the figure
#figure.subplot.right : 0.9 ## the right side of the subplots of the figure
#figure.subplot.bottom : 0.11 ## the bottom of the subplots of the figure
#figure.subplot.top : 0.88 ## the top of the subplots of the figure
#figure.subplot.wspace : 0.2 ## the amount of width reserved for space between subplots,
## expressed as a fraction of the average axis width
#figure.subplot.hspace : 0.2 ## the amount of height reserved for space between subplots,
## expressed as a fraction of the average axis height
## Figure layout
#figure.autolayout : False ## When True, automatically adjust subplot
## parameters to make the plot fit the figure
## using `tight_layout`
#figure.constrained_layout.use: False ## When True, automatically make plot
## elements fit on the figure. (Not compatible
## with `autolayout`, above).
#figure.constrained_layout.h_pad : 0.04167 ## Padding around axes objects. Float representing
#figure.constrained_layout.w_pad : 0.04167 ## inches. Default is 3./72. inches (3 pts)
#figure.constrained_layout.hspace : 0.02 ## Space between subplot groups. Float representing
#figure.constrained_layout.wspace : 0.02 ## a fraction of the subplot widths being separated.
#### IMAGES
#image.aspect : equal ## equal | auto | a number
#image.interpolation : nearest ## see help(imshow) for options
#image.cmap : viridis ## A colormap name, gray etc...
#image.lut : 256 ## the size of the colormap lookup table
#image.origin : upper ## lower | upper
#image.resample : True
#image.composite_image : True ## When True, all the images on a set of axes are
## combined into a single composite image before
## saving a figure as a vector graphics file,
## such as a PDF.
#### CONTOUR PLOTS
#contour.negative_linestyle : dashed ## string or on-off ink sequence
#contour.corner_mask : True ## True | False | legacy
#### ERRORBAR PLOTS
#errorbar.capsize : 0 ## length of end cap on error bars in pixels
#### HISTOGRAM PLOTS
#hist.bins : 10 ## The default number of histogram bins.
## If Numpy 1.11 or later is
## installed, may also be `auto`
#### SCATTER PLOTS
#scatter.marker : o ## The default marker type for scatter plots.
#scatter.edgecolors : face ## The default edgecolors for scatter plots.
#### Agg rendering
#### Warning: experimental, 2008/10/10
#agg.path.chunksize : 0 ## 0 to disable; values in the range
## 10000 to 100000 can improve speed slightly
## and prevent an Agg rendering failure
## when plotting very large data sets,
## especially if they are very gappy.
## It may cause minor artifacts, though.
## A value of 20000 is probably a good
## starting point.
#### PATHS
#path.simplify : True ## When True, simplify paths by removing "invisible"
## points to reduce file size and increase rendering
## speed
#path.simplify_threshold : 0.111111111111 ## The threshold of similarity below which
## vertices will be removed in the
## simplification process
#path.snap : True ## When True, rectilinear axis-aligned paths will be snapped to
## the nearest pixel when certain criteria are met. When False,
## paths will never be snapped.
#path.sketch : None ## May be none, or a 3-tuple of the form (scale, length,
## randomness).
## *scale* is the amplitude of the wiggle
## perpendicular to the line (in pixels). *length*
## is the length of the wiggle along the line (in
## pixels). *randomness* is the factor by which
## the length is randomly scaled.
#path.effects : [] ##
#### SAVING FIGURES
## the default savefig params can be different from the display params
## e.g., you may want a higher resolution, or to make the figure
## background white
#savefig.dpi : figure ## figure dots per inch or 'figure'
#savefig.facecolor : white ## figure facecolor when saving
#savefig.edgecolor : white ## figure edgecolor when saving
#savefig.format : png ## png, ps, pdf, svg
#savefig.bbox : standard ## 'tight' or 'standard'.
## 'tight' is incompatible with pipe-based animation
## backends but will workd with temporary file based ones:
## e.g. setting animation.writer to ffmpeg will not work,
## use ffmpeg_file instead
#savefig.pad_inches : 0.1 ## Padding to be used when bbox is set to 'tight'
#savefig.jpeg_quality: 95 ## when a jpeg is saved, the default quality parameter.
#savefig.directory : ~ ## default directory in savefig dialog box,
## leave empty to always use current working directory
#savefig.transparent : False ## setting that controls whether figures are saved with a
## transparent background by default
#savefig.orientation : portrait ## Orientation of saved figure
### tk backend params
#tk.window_focus : False ## Maintain shell focus for TkAgg
### ps backend params
#ps.papersize : letter ## auto, letter, legal, ledger, A0-A10, B0-B10
#ps.useafm : False ## use of afm fonts, results in small files
#ps.usedistiller : False ## can be: None, ghostscript or xpdf
## Experimental: may produce smaller files.
## xpdf intended for production of publication quality files,
## but requires ghostscript, xpdf and ps2eps
#ps.distiller.res : 6000 ## dpi
#ps.fonttype : 3 ## Output Type 3 (Type3) or Type 42 (TrueType)
### pdf backend params
#pdf.compression : 6 ## integer from 0 to 9
## 0 disables compression (good for debugging)
#pdf.fonttype : 3 ## Output Type 3 (Type3) or Type 42 (TrueType)
#pdf.use14corefonts : False
#pdf.inheritcolor : False
### svg backend params
#svg.image_inline : True ## write raster image data directly into the svg file
#svg.fonttype : path ## How to handle SVG fonts:
## none: Assume fonts are installed on the machine where the SVG will be viewed.
## path: Embed characters as paths -- supported by most SVG renderers
#svg.hashsalt : None ## if not None, use this string as hash salt
## instead of uuid4
### pgf parameter
#pgf.rcfonts : True
#pgf.preamble : ## see text.latex.preamble for documentation
#pgf.texsystem : xelatex
### docstring params
##docstring.hardcopy = False ## set this when you want to generate hardcopy docstring
## Event keys to interact with figures/plots via keyboard.
## Customize these settings according to your needs.
## Leave the field(s) empty if you don't need a key-map. (i.e., fullscreen : '')
#keymap.fullscreen : f, ctrl+f ## toggling
#keymap.home : h, r, home ## home or reset mnemonic
#keymap.back : left, c, backspace, MouseButton.BACK ## forward / backward keys
#keymap.forward : right, v, MouseButton.FORWARD ## for quick navigation
#keymap.pan : p ## pan mnemonic
#keymap.zoom : o ## zoom mnemonic
#keymap.save : s, ctrl+s ## saving current figure
#keymap.help : f1 ## display help about active tools
#keymap.quit : ctrl+w, cmd+w, q ## close the current figure
#keymap.quit_all : W, cmd+W, Q ## close all figures
#keymap.grid : g ## switching on/off major grids in current axes
#keymap.grid_minor : G ## switching on/off minor grids in current axes
#keymap.yscale : l ## toggle scaling of y-axes ('log'/'linear')
#keymap.xscale : k, L ## toggle scaling of x-axes ('log'/'linear')
#keymap.all_axes : a ## enable all axes
#keymap.copy : ctrl+c, cmd+c ## Copy figure to clipboard
###ANIMATION settings
#animation.html : none ## How to display the animation as HTML in
## the IPython notebook. 'html5' uses
## HTML5 video tag; 'jshtml' creates a
## Javascript animation
#animation.writer : ffmpeg ## MovieWriter 'backend' to use
#animation.codec : h264 ## Codec to use for writing movie
#animation.bitrate: -1 ## Controls size/quality tradeoff for movie.
## -1 implies let utility auto-determine
#animation.frame_format: png ## Controls frame format used by temp files
#animation.html_args: ## Additional arguments to pass to html writer
#animation.ffmpeg_path: ffmpeg ## Path to ffmpeg binary. Without full path
## $PATH is searched
#animation.ffmpeg_args: ## Additional arguments to pass to ffmpeg
#animation.avconv_path: avconv ## Path to avconv binary. Without full path
## $PATH is searched
#animation.avconv_args: ## Additional arguments to pass to avconv
#animation.convert_path: convert ## Path to ImageMagick's convert binary.
## On Windows use the full path since convert
## is also the name of a system tool.
#animation.convert_args: ## Additional arguments to pass to convert
#animation.embed_limit : 20.0 ## Limit, in MB, of size of base64 encoded
## animation in HTML (i.e. IPython notebook)
```
## Download
- [Download Python source code: customizing.py](https://matplotlib.org/_downloads/acbde7c6b91c31c4a29433e87403c871/customizing.py)
- [Download Jupyter notebook: customizing.ipynb](https://matplotlib.org/_downloads/a0acd54a96b40e271115ea0964417a12/customizing.ipynb)

View File

@@ -0,0 +1,348 @@
---
sidebarDepth: 3
sidebar: auto
---
# Image tutorial
A short tutorial on plotting images with Matplotlib.
## Startup commands
First, let's start IPython. It is a most excellent enhancement to the
standard Python prompt, and it ties in especially well with
Matplotlib. Start IPython either at a shell, or the IPython Notebook now.
With IPython started, we now need to connect to a GUI event loop. This
tells IPython where (and how) to display plots. To connect to a GUI
loop, execute the **%matplotlib** magic at your IPython prompt. There's more
detail on exactly what this does at [IPython's documentation on GUI
event loops](http://ipython.org/ipython-doc/2/interactive/reference.html#gui-event-loop-support).
If you're using IPython Notebook, the same commands are available, but
people commonly use a specific argument to the %matplotlib magic:
``` python
In [1]: %matplotlib inline
```
This turns on inline plotting, where plot graphics will appear in your
notebook. This has important implications for interactivity. For inline plotting, commands in
cells below the cell that outputs a plot will not affect the plot. For example,
changing the color map is not possible from cells below the cell that creates a plot.
However, for other backends, such as Qt5, that open a separate window,
cells below those that create the plot will change the plot - it is a
live object in memory.
This tutorial will use matplotlib's imperative-style plotting
interface, pyplot. This interface maintains global state, and is very
useful for quickly and easily experimenting with various plot
settings. The alternative is the object-oriented interface, which is also
very powerful, and generally more suitable for large application
development. If you'd like to learn about the object-oriented
interface, a great place to start is our [Usage guide](usage.html). For now, let's get on
with the imperative-style approach:
``` python
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
```
## Importing image data into Numpy arrays
Loading image data is supported by the [Pillow](https://pillow.readthedocs.io/en/latest/) library. Natively, Matplotlib
only supports PNG images. The commands shown below fall back on Pillow if
the native read fails.
The image used in this example is a PNG file, but keep that Pillow
requirement in mind for your own data.
Here's the image we're going to play with:
![stinkbug](https://matplotlib.org/_images/stinkbug.png)
It's a 24-bit RGB PNG image (8 bits for each of R, G, B). Depending
on where you get your data, the other kinds of image that you'll most
likely encounter are RGBA images, which allow for transparency, or
single-channel grayscale (luminosity) images. You can right click on
it and choose "Save image as" to download it to your computer for the
rest of this tutorial.
And here we go...
``` python
img = mpimg.imread('../../doc/_static/stinkbug.png')
print(img)
```
Out:
```
[[[0.40784314 0.40784314 0.40784314]
[0.40784314 0.40784314 0.40784314]
[0.40784314 0.40784314 0.40784314]
...
[0.42745098 0.42745098 0.42745098]
[0.42745098 0.42745098 0.42745098]
[0.42745098 0.42745098 0.42745098]]
[[0.4117647 0.4117647 0.4117647 ]
[0.4117647 0.4117647 0.4117647 ]
[0.4117647 0.4117647 0.4117647 ]
...
[0.42745098 0.42745098 0.42745098]
[0.42745098 0.42745098 0.42745098]
[0.42745098 0.42745098 0.42745098]]
[[0.41960785 0.41960785 0.41960785]
[0.41568628 0.41568628 0.41568628]
[0.41568628 0.41568628 0.41568628]
...
[0.43137255 0.43137255 0.43137255]
[0.43137255 0.43137255 0.43137255]
[0.43137255 0.43137255 0.43137255]]
...
[[0.4392157 0.4392157 0.4392157 ]
[0.43529412 0.43529412 0.43529412]
[0.43137255 0.43137255 0.43137255]
...
[0.45490196 0.45490196 0.45490196]
[0.4509804 0.4509804 0.4509804 ]
[0.4509804 0.4509804 0.4509804 ]]
[[0.44313726 0.44313726 0.44313726]
[0.44313726 0.44313726 0.44313726]
[0.4392157 0.4392157 0.4392157 ]
...
[0.4509804 0.4509804 0.4509804 ]
[0.44705883 0.44705883 0.44705883]
[0.44705883 0.44705883 0.44705883]]
[[0.44313726 0.44313726 0.44313726]
[0.4509804 0.4509804 0.4509804 ]
[0.4509804 0.4509804 0.4509804 ]
...
[0.44705883 0.44705883 0.44705883]
[0.44705883 0.44705883 0.44705883]
[0.44313726 0.44313726 0.44313726]]]
```
Note the dtype there - float32. Matplotlib has rescaled the 8 bit
data from each channel to floating point data between 0.0 and 1.0. As
a side note, the only datatype that Pillow can work with is uint8.
Matplotlib plotting can handle float32 and uint8, but image
reading/writing for any format other than PNG is limited to uint8
data. Why 8 bits? Most displays can only render 8 bits per channel
worth of color gradation. Why can they only render 8 bits/channel?
Because that's about all the human eye can see. More here (from a
photography standpoint): [Luminous Landscape bit depth tutorial](https://luminous-landscape.com/bit-depth/).
Each inner list represents a pixel. Here, with an RGB image, there
are 3 values. Since it's a black and white image, R, G, and B are all
similar. An RGBA (where A is alpha, or transparency), has 4 values
per inner list, and a simple luminance image just has one value (and
is thus only a 2-D array, not a 3-D array). For RGB and RGBA images,
matplotlib supports float32 and uint8 data types. For grayscale,
matplotlib supports only float32. If your array data does not meet
one of these descriptions, you need to rescale it.
## Plotting numpy arrays as images
So, you have your data in a numpy array (either by importing it, or by
generating it). Let's render it. In Matplotlib, this is performed
using the [``imshow()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow) function. Here we'll grab
the plot object. This object gives you an easy way to manipulate the
plot from the prompt.
``` python
imgplot = plt.imshow(img)
```
![sphx_glr_images_001](https://matplotlib.org/_images/sphx_glr_images_001.png)
You can also plot any numpy array.
### Applying pseudocolor schemes to image plots
Pseudocolor can be a useful tool for enhancing contrast and
visualizing your data more easily. This is especially useful when
making presentations of your data using projectors - their contrast is
typically quite poor.
Pseudocolor is only relevant to single-channel, grayscale, luminosity
images. We currently have an RGB image. Since R, G, and B are all
similar (see for yourself above or in your data), we can just pick one
channel of our data:
``` python
lum_img = img[:, :, 0]
# This is array slicing. You can read more in the `Numpy tutorial
# <https://docs.scipy.org/doc/numpy/user/quickstart.html>`_.
plt.imshow(lum_img)
```
![sphx_glr_images_002](https://matplotlib.org/_images/sphx_glr_images_002.png)
Now, with a luminosity (2D, no color) image, the default colormap (aka lookup table,
LUT), is applied. The default is called viridis. There are plenty of
others to choose from.
``` python
plt.imshow(lum_img, cmap="hot")
```
![sphx_glr_images_003](https://matplotlib.org/_images/sphx_glr_images_003.png)
Note that you can also change colormaps on existing plot objects using the
``set_cmap()`` method:
``` python
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('nipy_spectral')
```
![sphx_glr_images_004](https://matplotlib.org/_images/sphx_glr_images_004.png)
::: tip Note
However, remember that in the IPython notebook with the inline backend,
you can't make changes to plots that have already been rendered. If you
create imgplot here in one cell, you cannot call set_cmap() on it in a later
cell and expect the earlier plot to change. Make sure that you enter these
commands together in one cell. plt commands will not change plots from earlier
cells.
:::
There are many other colormap schemes available. See the [list and
images of the colormaps](https://matplotlib.org/colors/colormaps.html).
### Color scale reference
It's helpful to have an idea of what value a color represents. We can
do that by adding color bars.
``` python
imgplot = plt.imshow(lum_img)
plt.colorbar()
```
![sphx_glr_images_005](https://matplotlib.org/_images/sphx_glr_images_005.png)
This adds a colorbar to your existing figure. This won't
automatically change if you change you switch to a different
colormap - you have to re-create your plot, and add in the colorbar
again.
### Examining a specific data range
Sometimes you want to enhance the contrast in your image, or expand
the contrast in a particular region while sacrificing the detail in
colors that don't vary much, or don't matter. A good tool to find
interesting regions is the histogram. To create a histogram of our
image data, we use the [``hist()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.hist.html#matplotlib.pyplot.hist) function.
``` python
plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
```
![sphx_glr_images_006](https://matplotlib.org/_images/sphx_glr_images_006.png)
Most often, the "interesting" part of the image is around the peak,
and you can get extra contrast by clipping the regions above and/or
below the peak. In our histogram, it looks like there's not much
useful information in the high end (not many white things in the
image). Let's adjust the upper limit, so that we effectively "zoom in
on" part of the histogram. We do this by passing the clim argument to
imshow. You could also do this by calling the
``set_clim()`` method of the image plot
object, but make sure that you do so in the same cell as your plot
command when working with the IPython Notebook - it will not change
plots from earlier cells.
You can specify the clim in the call to ``plot``.
``` python
imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))
```
![sphx_glr_images_007](https://matplotlib.org/_images/sphx_glr_images_007.png)
You can also specify the clim using the returned object
``` python
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
imgplot = plt.imshow(lum_img)
a.set_title('Before')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
a = fig.add_subplot(1, 2, 2)
imgplot = plt.imshow(lum_img)
imgplot.set_clim(0.0, 0.7)
a.set_title('After')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
```
![sphx_glr_images_008](https://matplotlib.org/_images/sphx_glr_images_008.png)
### Array Interpolation schemes
Interpolation calculates what the color or value of a pixel "should"
be, according to different mathematical schemes. One common place
that this happens is when you resize an image. The number of pixels
change, but you want the same information. Since pixels are discrete,
there's missing space. Interpolation is how you fill that space.
This is why your images sometimes come out looking pixelated when you
blow them up. The effect is more pronounced when the difference
between the original image and the expanded image is greater. Let's
take our image and shrink it. We're effectively discarding pixels,
only keeping a select few. Now when we plot it, that data gets blown
up to the size on your screen. The old pixels aren't there anymore,
and the computer has to draw in pixels to fill that space.
We'll use the Pillow library that we used to load the image also to resize
the image.
``` python
from PIL import Image
img = Image.open('../../doc/_static/stinkbug.png')
img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
imgplot = plt.imshow(img)
```
![sphx_glr_images_009](https://matplotlib.org/_images/sphx_glr_images_009.png)
Here we have the default interpolation, bilinear, since we did not
give [``imshow()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow) any interpolation argument.
Let's try some others. Here's "nearest", which does no interpolation.
``` python
imgplot = plt.imshow(img, interpolation="nearest")
```
![sphx_glr_images_010](https://matplotlib.org/_images/sphx_glr_images_010.png)
and bicubic:
``` python
imgplot = plt.imshow(img, interpolation="bicubic")
```
![sphx_glr_images_011](https://matplotlib.org/_images/sphx_glr_images_011.png)
Bicubic interpolation is often used when blowing up photos - people
tend to prefer blurry over pixelated.
**Total running time of the script:** ( 0 minutes 1.829 seconds)
## Download
- [Download Python source code: images.py](https://matplotlib.org/_downloads/b9ccc225a9488811ec7ceeb6dfc7d21f/images.py)
- [Download Jupyter notebook: images.ipynb](https://matplotlib.org/_downloads/ec8d45ccc5387a8e56bc5e286ae92234/images.ipynb)

View File

@@ -0,0 +1,325 @@
---
sidebarDepth: 3
sidebar: auto
---
# The Lifecycle of a Plot
This tutorial aims to show the beginning, middle, and end of a single
visualization using Matplotlib. We'll begin with some raw data and
end by saving a figure of a customized visualization. Along the way we'll try
to highlight some neat features and best-practices using Matplotlib.
::: tip Note
This tutorial is based off of
[this excellent blog post](http://pbpython.com/effective-matplotlib.html)
by Chris Moffitt. It was transformed into this tutorial by Chris Holdgraf.
:::
## A note on the Object-Oriented API vs Pyplot
Matplotlib has two interfaces. The first is an object-oriented (OO)
interface. In this case, we utilize an instance of [``axes.Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes)
in order to render visualizations on an instance of [``figure.Figure``](https://matplotlib.orgapi/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure).
The second is based on MATLAB and uses a state-based interface. This is
encapsulated in the ``pyplot`` module. See the [pyplot tutorials](pyplot.html) for a more in-depth look at the pyplot
interface.
Most of the terms are straightforward but the main thing to remember
is that:
- The Figure is the final image that may contain 1 or more Axes.
- The Axes represent an individual plot (don't confuse this with the word
"axis", which refers to the x/y axis of a plot).
We call methods that do the plotting directly from the Axes, which gives
us much more flexibility and power in customizing our plot.
::: tip Note
In general, try to use the object-oriented interface over the pyplot
interface.
:::
## Our data
We'll use the data from the post from which this tutorial was derived.
It contains sales information for a number of companies.
``` python
# sphinx_gallery_thumbnail_number = 10
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
data = {'Barton LLC': 109438.50,
'Frami, Hills and Schmidt': 103569.59,
'Fritsch, Russel and Anderson': 112214.71,
'Jerde-Hilpert': 112591.43,
'Keeling LLC': 100934.30,
'Koepp Ltd': 103660.54,
'Kulas Inc': 137351.96,
'Trantow-Barrows': 123381.38,
'White-Trantow': 135841.99,
'Will LLC': 104437.60}
group_data = list(data.values())
group_names = list(data.keys())
group_mean = np.mean(group_data)
```
## Getting started
This data is naturally visualized as a barplot, with one bar per
group. To do this with the object-oriented approach, we'll first generate
an instance of [``figure.Figure``](https://matplotlib.orgapi/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure) and
[``axes.Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes). The Figure is like a canvas, and the Axes
is a part of that canvas on which we will make a particular visualization.
::: tip Note
Figures can have multiple axes on them. For information on how to do this,
see the [Tight Layout tutorial](https://matplotlib.org/intermediate/tight_layout_guide.html).
:::
``` python
fig, ax = plt.subplots()
```
![sphx_glr_lifecycle_001](https://matplotlib.org/_images/sphx_glr_lifecycle_001.png)
Now that we have an Axes instance, we can plot on top of it.
``` python
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
```
![sphx_glr_lifecycle_002](https://matplotlib.org/_images/sphx_glr_lifecycle_002.png)
## Controlling the style
There are many styles available in Matplotlib in order to let you tailor
your visualization to your needs. To see a list of styles, we can use
``pyplot.style``.
``` python
print(plt.style.available)
```
Out:
```
['seaborn-dark', 'dark_background', 'seaborn-pastel', 'seaborn-colorblind', 'tableau-colorblind10', 'seaborn-notebook', 'seaborn-dark-palette', 'grayscale', 'seaborn-poster', 'seaborn', 'bmh', 'seaborn-talk', 'seaborn-ticks', '_classic_test', 'ggplot', 'seaborn-white', 'classic', 'Solarize_Light2', 'seaborn-paper', 'fast', 'fivethirtyeight', 'seaborn-muted', 'seaborn-whitegrid', 'seaborn-darkgrid', 'seaborn-bright', 'seaborn-deep']
```
You can activate a style with the following:
``` python
plt.style.use('fivethirtyeight')
```
Now let's remake the above plot to see how it looks:
``` python
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
```
![sphx_glr_lifecycle_003](https://matplotlib.org/_images/sphx_glr_lifecycle_003.png)
The style controls many things, such as color, linewidths, backgrounds,
etc.
## Customizing the plot
Now we've got a plot with the general look that we want, so let's fine-tune
it so that it's ready for print. First let's rotate the labels on the x-axis
so that they show up more clearly. We can gain access to these labels
with the [``axes.Axes.get_xticklabels()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.get_xticklabels.html#matplotlib.axes.Axes.get_xticklabels) method:
``` python
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
```
![sphx_glr_lifecycle_004](https://matplotlib.org/_images/sphx_glr_lifecycle_004.png)
If we'd like to set the property of many items at once, it's useful to use
the [``pyplot.setp()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.setp.html#matplotlib.pyplot.setp) function. This will take a list (or many lists) of
Matplotlib objects, and attempt to set some style element of each one.
``` python
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
```
![sphx_glr_lifecycle_005](https://matplotlib.org/_images/sphx_glr_lifecycle_005.png)
It looks like this cut off some of the labels on the bottom. We can
tell Matplotlib to automatically make room for elements in the figures
that we create. To do this we'll set the ``autolayout`` value of our
rcParams. For more information on controlling the style, layout, and
other features of plots with rcParams, see
[Customizing Matplotlib with style sheets and rcParams](customizing.html).
``` python
plt.rcParams.update({'figure.autolayout': True})
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
```
![sphx_glr_lifecycle_006](https://matplotlib.org/_images/sphx_glr_lifecycle_006.png)
Next, we'll add labels to the plot. To do this with the OO interface,
we can use the [``axes.Axes.set()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set.html#matplotlib.axes.Axes.set) method to set properties of this
Axes object.
``` python
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
```
![sphx_glr_lifecycle_007](https://matplotlib.org/_images/sphx_glr_lifecycle_007.png)
We can also adjust the size of this plot using the [``pyplot.subplots()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.subplots.html#matplotlib.pyplot.subplots)
function. We can do this with the ``figsize`` kwarg.
::: tip Note
While indexing in NumPy follows the form (row, column), the figsize
kwarg follows the form (width, height). This follows conventions in
visualization, which unfortunately are different from those of linear
algebra.
:::
``` python
fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
```
![sphx_glr_lifecycle_008](https://matplotlib.org/_images/sphx_glr_lifecycle_008.png)
For labels, we can specify custom formatting guidelines in the form of
functions by using the [``ticker.FuncFormatter``](https://matplotlib.orgapi/ticker_api.html#matplotlib.ticker.FuncFormatter) class. Below we'll
define a function that takes an integer as input, and returns a string
as an output.
``` python
def currency(x, pos):
"""The two args are the value and tick position"""
if x >= 1e6:
s = '${:1.1f}M'.format(x*1e-6)
else:
s = '${:1.0f}K'.format(x*1e-3)
return s
formatter = FuncFormatter(currency)
```
We can then apply this formatter to the labels on our plot. To do this,
we'll use the ``xaxis`` attribute of our axis. This lets you perform
actions on a specific axis on our plot.
``` python
fig, ax = plt.subplots(figsize=(6, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(formatter)
```
![sphx_glr_lifecycle_009](https://matplotlib.org/_images/sphx_glr_lifecycle_009.png)
## Combining multiple visualizations
It is possible to draw multiple plot elements on the same instance of
[``axes.Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes). To do this we simply need to call another one of
the plot methods on that axes object.
``` python
fig, ax = plt.subplots(figsize=(8, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
# Add a vertical line, here we set the style in the function call
ax.axvline(group_mean, ls='--', color='r')
# Annotate new companies
for group in [3, 5, 8]:
ax.text(145000, group, "New Company", fontsize=10,
verticalalignment="center")
# Now we'll move our title up since it's getting a little cramped
ax.title.set(y=1.05)
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(formatter)
ax.set_xticks([0, 25e3, 50e3, 75e3, 100e3, 125e3])
fig.subplots_adjust(right=.1)
plt.show()
```
![sphx_glr_lifecycle_010](https://matplotlib.org/_images/sphx_glr_lifecycle_010.png)
## Saving our plot
Now that we're happy with the outcome of our plot, we want to save it to
disk. There are many file formats we can save to in Matplotlib. To see
a list of available options, use:
``` python
print(fig.canvas.get_supported_filetypes())
```
Out:
```
{'ps': 'Postscript', 'eps': 'Encapsulated Postscript', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}
```
We can then use the [``figure.Figure.savefig()``](https://matplotlib.orgapi/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.savefig) in order to save the figure
to disk. Note that there are several useful flags we'll show below:
- ``transparent=True`` makes the background of the saved figure transparent
if the format supports it.
- ``dpi=80`` controls the resolution (dots per square inch) of the output.
- ``bbox_inches="tight"`` fits the bounds of the figure to our plot.
``` python
# Uncomment this line to save the figure.
# fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")
```
**Total running time of the script:** ( 0 minutes 1.566 seconds)
## Download
- [Download Python source code: lifecycle.py](https://matplotlib.org/_downloads/9f5af95225ff5984a6cc962463c43459/lifecycle.py)
- [Download Jupyter notebook: lifecycle.ipynb](https://matplotlib.org/_downloads/db19d93870c5df97263c5f5a2e835466/lifecycle.ipynb)

View File

@@ -0,0 +1,568 @@
---
sidebarDepth: 3
sidebar: auto
---
# Pyplot tutorial
An introduction to the pyplot interface.
## Intro to pyplot
[``matplotlib.pyplot``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot) is a collection of command style functions
that make matplotlib work like MATLAB.
Each ``pyplot`` function makes
some change to a figure: e.g., creates a figure, creates a plotting area
in a figure, plots some lines in a plotting area, decorates the plot
with labels, etc.
In [``matplotlib.pyplot``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot) various states are preserved
across function calls, so that it keeps track of things like
the current figure and plotting area, and the plotting
functions are directed to the current axes (please note that "axes" here
and in most places in the documentation refers to the *axes*
[part of a figure](usage.html#figure-parts)
and not the strict mathematical term for more than one axis).
::: tip Note
the pyplot API is generally less-flexible than the object-oriented API.
Most of the function calls you see here can also be called as methods
from an ``Axes`` object. We recommend browsing the tutorials and
examples to see how this works.
:::
Generating visualizations with pyplot is very quick:
``` python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
```
![sphx_glr_pyplot_001](https://matplotlib.org/_images/sphx_glr_pyplot_001.png)
You may be wondering why the x-axis ranges from 0-3 and the y-axis
from 1-4. If you provide a single list or array to the
[``plot()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) command, matplotlib assumes it is a
sequence of y values, and automatically generates the x values for
you. Since python ranges start with 0, the default x vector has the
same length as y but starts with 0. Hence the x data are
``[0,1,2,3]``.
[``plot()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) is a versatile command, and will take
an arbitrary number of arguments. For example, to plot x versus y,
you can issue the command:
``` python
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
```
![sphx_glr_pyplot_002](https://matplotlib.org/_images/sphx_glr_pyplot_002.png)
### Formatting the style of your plot
For every x, y pair of arguments, there is an optional third argument
which is the format string that indicates the color and line type of
the plot. The letters and symbols of the format string are from
MATLAB, and you concatenate a color string with a line style string.
The default format string is 'b-', which is a solid blue line. For
example, to plot the above with red circles, you would issue
``` python
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
```
![sphx_glr_pyplot_003](https://matplotlib.org/_images/sphx_glr_pyplot_003.png)
See the [``plot()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) documentation for a complete
list of line styles and format strings. The
[``axis()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.axis.html#matplotlib.pyplot.axis) command in the example above takes a
list of ``[xmin, xmax, ymin, ymax]`` and specifies the viewport of the
axes.
If matplotlib were limited to working with lists, it would be fairly
useless for numeric processing. Generally, you will use [numpy](http://www.numpy.org) arrays. In fact, all sequences are
converted to numpy arrays internally. The example below illustrates a
plotting several lines with different format styles in one command
using arrays.
``` python
import numpy as np
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
```
![sphx_glr_pyplot_004](https://matplotlib.org/_images/sphx_glr_pyplot_004.png)
## Plotting with keyword strings
There are some instances where you have data in a format that lets you
access particular variables with strings. For example, with
[``numpy.recarray``](https://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.html#numpy.recarray) or [``pandas.DataFrame``](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame).
Matplotlib allows you provide such an object with
the ``data`` keyword argument. If provided, then you may generate plots with
the strings corresponding to these variables.
``` python
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
```
![sphx_glr_pyplot_005](https://matplotlib.org/_images/sphx_glr_pyplot_005.png)
## Plotting with categorical variables
It is also possible to create a plot using categorical variables.
Matplotlib allows you to pass categorical variables directly to
many plotting functions. For example:
``` python
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]
plt.figure(figsize=(9, 3))
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
```
![sphx_glr_pyplot_006](https://matplotlib.org/_images/sphx_glr_pyplot_006.png)
## Controlling line properties
Lines have many attributes that you can set: linewidth, dash style,
antialiased, etc; see [``matplotlib.lines.Line2D``](https://matplotlib.orgapi/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D). There are
several ways to set line properties
- Use keyword args:
``` python
plt.plot(x, y, linewidth=2.0)
```
- Use the setter methods of a ``Line2D`` instance. ``plot`` returns a list
of ``Line2D`` objects; e.g., ``line1, line2 = plot(x1, y1, x2, y2)``. In the code
below we will suppose that we have only
one line so that the list returned is of length 1. We use tuple unpacking with
``line,`` to get the first element of that list:
``` python
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialiasing
```
- Use the [``setp()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.setp.html#matplotlib.pyplot.setp) command. The example below
uses a MATLAB-style command to set multiple properties
on a list of lines. ``setp`` works transparently with a list of objects
or a single object. You can either use python keyword arguments or
MATLAB-style string/value pairs:
``` python
lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
```
Here are the available [``Line2D``](https://matplotlib.orgapi/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D) properties.
---
Property
Value Type
```
alpha
float
animated
[True | False]
antialiased or aa
[True | False]
clip_box
a matplotlib.transform.Bbox instance
clip_on
[True | False]
clip_path
a Path instance and a Transform instance, a Patch
color or c
any matplotlib color
contains
the hit testing function
dash_capstyle
['butt' | 'round' | 'projecting']
dash_joinstyle
['miter' | 'round' | 'bevel']
dashes
sequence of on/off ink in points
data
(np.array xdata, np.array ydata)
figure
a matplotlib.figure.Figure instance
label
any string
linestyle or ls
[ '-' | '--' | '-.' | ':' | 'steps' | ...]
linewidth or lw
float value in points
marker
[ '+' | ',' | '.' | '1' | '2' | '3' | '4' ]
markeredgecolor or mec
any matplotlib color
markeredgewidth or mew
float value in points
markerfacecolor or mfc
any matplotlib color
markersize or ms
float
markevery
[ None | integer | (startind, stride) ]
picker
used in interactive line selection
pickradius
the line pick selection radius
solid_capstyle
['butt' | 'round' | 'projecting']
solid_joinstyle
['miter' | 'round' | 'bevel']
transform
a matplotlib.transforms.Transform instance
visible
[True | False]
xdata
np.array
ydata
np.array
zorder
any number
```
To get a list of settable line properties, call the
[``setp()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.setp.html#matplotlib.pyplot.setp) function with a line or lines
as argument
``` python
In [69]: lines = plt.plot([1, 2, 3])
In [70]: plt.setp(lines)
alpha: float
animated: [True | False]
antialiased or aa: [True | False]
...snip
```
## Working with multiple figures and axes
MATLAB, and [``pyplot``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot), have the concept of the current
figure and the current axes. All plotting commands apply to the
current axes. The function [``gca()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.gca.html#matplotlib.pyplot.gca) returns the
current axes (a [``matplotlib.axes.Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes) instance), and
[``gcf()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.gcf.html#matplotlib.pyplot.gcf) returns the current figure
([``matplotlib.figure.Figure``](https://matplotlib.orgapi/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure) instance). Normally, you don't have
to worry about this, because it is all taken care of behind the
scenes. Below is a script to create two subplots.
``` python
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
```
![sphx_glr_pyplot_007](https://matplotlib.org/_images/sphx_glr_pyplot_007.png)
The [``figure()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure) command here is optional because
``figure(1)`` will be created by default, just as a ``subplot(111)``
will be created by default if you don't manually specify any axes. The
[``subplot()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.subplot.html#matplotlib.pyplot.subplot) command specifies ``numrows,
numcols, plot_number`` where ``plot_number`` ranges from 1 to
``numrows*numcols``. The commas in the ``subplot`` command are
optional if ``numrows*numcols<10``. So ``subplot(211)`` is identical
to ``subplot(2, 1, 1)``.
You can create an arbitrary number of subplots
and axes. If you want to place an axes manually, i.e., not on a
rectangular grid, use the [``axes()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.axes.html#matplotlib.pyplot.axes) command,
which allows you to specify the location as ``axes([left, bottom,
width, height])`` where all values are in fractional (0 to 1)
coordinates. See [Axes Demo](https://matplotlib.orggallery/subplots_axes_and_figures/axes_demo.html) for an example of
placing axes manually and [Basic Subplot Demo](https://matplotlib.orggallery/subplots_axes_and_figures/subplot_demo.html) for an
example with lots of subplots.
You can create multiple figures by using multiple
[``figure()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure) calls with an increasing figure
number. Of course, each figure can contain as many axes and subplots
as your heart desires:
``` python
import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4, 5, 6])
plt.figure(2) # a second figure
plt.plot([4, 5, 6]) # creates a subplot(111) by default
plt.figure(1) # figure 1 current; subplot(212) still current
plt.subplot(211) # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title
```
You can clear the current figure with [``clf()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.clf.html#matplotlib.pyplot.clf)
and the current axes with [``cla()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.cla.html#matplotlib.pyplot.cla). If you find
it annoying that states (specifically the current image, figure and axes)
are being maintained for you behind the scenes, don't despair: this is just a thin
stateful wrapper around an object oriented API, which you can use
instead (see [Artist tutorial](https://matplotlib.org/intermediate/artists.html))
If you are making lots of figures, you need to be aware of one
more thing: the memory required for a figure is not completely
released until the figure is explicitly closed with
[``close()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.close.html#matplotlib.pyplot.close). Deleting all references to the
figure, and/or using the window manager to kill the window in which
the figure appears on the screen, is not enough, because pyplot
maintains internal references until [``close()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.close.html#matplotlib.pyplot.close)
is called.
## Working with text
The [``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text) command can be used to add text in
an arbitrary location, and the [``xlabel()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.xlabel.html#matplotlib.pyplot.xlabel),
[``ylabel()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.ylabel.html#matplotlib.pyplot.ylabel) and [``title()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.title.html#matplotlib.pyplot.title)
are used to add text in the indicated locations (see [Text in Matplotlib Plots](https://matplotlib.org/text/text_intro.html)
for a more detailed example)
``` python
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
```
![sphx_glr_pyplot_008](https://matplotlib.org/_images/sphx_glr_pyplot_008.png)
All of the [``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text) commands return an
[``matplotlib.text.Text``](https://matplotlib.orgapi/text_api.html#matplotlib.text.Text) instance. Just as with with lines
above, you can customize the properties by passing keyword arguments
into the text functions or using [``setp()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.setp.html#matplotlib.pyplot.setp):
``` python
t = plt.xlabel('my data', fontsize=14, color='red')
```
These properties are covered in more detail in [Text properties and layout](https://matplotlib.org/text/text_props.html).
### Using mathematical expressions in text
matplotlib accepts TeX equation expressions in any text expression.
For example to write the expression \(\sigma_i=15\) in the title,
you can write a TeX expression surrounded by dollar signs:
``` python
plt.title(r'$\sigma_i=15$')
```
The ``r`` preceding the title string is important -- it signifies
that the string is a *raw* string and not to treat backslashes as
python escapes. matplotlib has a built-in TeX expression parser and
layout engine, and ships its own math fonts -- for details see
[Writing mathematical expressions](https://matplotlib.org/text/mathtext.html). Thus you can use mathematical text across platforms
without requiring a TeX installation. For those who have LaTeX and
dvipng installed, you can also use LaTeX to format your text and
incorporate the output directly into your display figures or saved
postscript -- see [Text rendering With LaTeX](https://matplotlib.org/text/usetex.html).
### Annotating text
The uses of the basic [``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text) command above
place text at an arbitrary position on the Axes. A common use for
text is to annotate some feature of the plot, and the
[``annotate()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.annotate.html#matplotlib.pyplot.annotate) method provides helper
functionality to make annotations easy. In an annotation, there are
two points to consider: the location being annotated represented by
the argument ``xy`` and the location of the text ``xytext``. Both of
these arguments are ``(x,y)`` tuples.
``` python
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2, 2)
plt.show()
```
![sphx_glr_pyplot_009](https://matplotlib.org/_images/sphx_glr_pyplot_009.png)
In this basic example, both the ``xy`` (arrow tip) and ``xytext``
locations (text location) are in data coordinates. There are a
variety of other coordinate systems one can choose -- see
[Basic annotation](https://matplotlib.org/text/annotations.html#annotations-tutorial) and [Advanced Annotation](https://matplotlib.org/text/annotations.html#plotting-guide-annotation) for
details. More examples can be found in
[Annotating Plots](https://matplotlib.orggallery/text_labels_and_annotations/annotation_demo.html).
## Logarithmic and other nonlinear axes
[``matplotlib.pyplot``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot) supports not only linear axis scales, but also
logarithmic and logit scales. This is commonly used if data spans many orders
of magnitude. Changing the scale of an axis is easy:
An example of four plots with the same data and different scales for the y axis
is shown below.
``` python
from matplotlib.ticker import NullFormatter # useful for `logit` scale
# Fixing random state for reproducibility
np.random.seed(19680801)
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
plt.figure()
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
plt.show()
```
![sphx_glr_pyplot_010](https://matplotlib.org/_images/sphx_glr_pyplot_010.png)
It is also possible to add your own scale, see [Developer's guide for creating scales and transformations](https://matplotlib.orgdevel/add_new_projection.html#adding-new-scales) for
details.
**Total running time of the script:** ( 0 minutes 1.262 seconds)
## Download
- [Download Python source code: pyplot.py](https://matplotlib.org/_downloads/2dc0b600c5a44dd0a9ee2d1b44a67235/pyplot.py)
- [Download Jupyter notebook: pyplot.ipynb](https://matplotlib.org/_downloads/a5d09473b82821f8a7203a3d071d953a/pyplot.ipynb)

View File

@@ -0,0 +1,411 @@
---
sidebarDepth: 3
sidebar: auto
---
# Sample plots in Matplotlib
Here you'll find a host of example plots with the code that
generated them.
## Line Plot
Here's how to create a line plot with text labels using
[``plot()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot).
<center>
<a href="/gallery/lines_bars_and_markers/simple_plot.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_simple_plot_0011.png">
</a>
<p>
<b>Simple Plot</b>
</p>
</center>
## Multiple subplots in one figure
Multiple axes (i.e. subplots) are created with the
[``subplot()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplot.html#matplotlib.pyplot.subplot) function:
<center>
<a href="/gallery/subplots_axes_and_figures/subplot.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_subplot_0011.png">
</a>
<p>
<b>Subplot</b>
</p>
</center>
## Images
Matplotlib can display images (assuming equally spaced
horizontal dimensions) using the [``imshow()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow) function.
<center>
<a href="/gallery/images_contours_and_fields/image_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_image_demo_0031.png">
</a>
</center>
**Example of using [``imshow()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html#matplotlib.pyplot.imshow) to display a CT scan**
## Contouring and pseudocolor
The [``pcolormesh()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html#matplotlib.pyplot.pcolormesh) function can make a colored
representation of a two-dimensional array, even if the horizontal dimensions
are unevenly spaced. The
[``contour()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.contour.html#matplotlib.pyplot.contour) function is another way to represent
the same data:
<center>
<a href="/gallery/images_contours_and_fields/pcolormesh_levels.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_pcolormesh_levels_0011.png">
</a>
</center>
**Example comparing [``pcolormesh()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html#matplotlib.pyplot.pcolormesh) and [``contour()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.contour.html#matplotlib.pyplot.contour) for plotting two-dimensional data**
## Histograms
The [``hist()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html#matplotlib.pyplot.hist) function automatically generates
histograms and returns the bin counts or probabilities:
<center>
<a href="/gallery/statistics/histogram_features.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_histogram_features_0011.png">
</a>
<p>
<b>Histogram Features</b>
</p>
</center>
## Paths
You can add arbitrary paths in Matplotlib using the
[``matplotlib.path``](https://matplotlib.org/api/path_api.html#module-matplotlib.path) module:
<center>
<a href="/gallery/shapes_and_collections/path_patch.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_path_patch_0011.png">
</a>
<p>
<b>Path Patch</b>
</p>
</center>
## Three-dimensional plotting
The mplot3d toolkit (see [Getting started](https://matplotlib.org//toolkits/mplot3d.html#toolkit-mplot3d-tutorial) and
[3D plotting](https://matplotlib.org/gallery/index.html#mplot3d-examples-index)) has support for simple 3d graphs
including surface, wireframe, scatter, and bar charts.
<center>
<a href="/gallery/mplot3d/surface3d.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_surface3d_0011.png">
</a>
<p>
<b>Surface3d</b>
</p>
</center>
Thanks to John Porter, Jonathon Taylor, Reinier Heeres, and Ben Root for
the ``mplot3d`` toolkit. This toolkit is included with all standard Matplotlib
installs.
## Streamplot
The [``streamplot()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.streamplot.html#matplotlib.pyplot.streamplot) function plots the streamlines of
a vector field. In addition to simply plotting the streamlines, it allows you
to map the colors and/or line widths of streamlines to a separate parameter,
such as the speed or local intensity of the vector field.
<center>
<a href="/gallery/images_contours_and_fields/plot_streamplot.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_plot_streamplot_0011.png">
</a>
<p>
<b>Streamplot with various plotting options.</b>
</p>
</center>
This feature complements the [``quiver()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.quiver.html#matplotlib.pyplot.quiver) function for
plotting vector fields. Thanks to Tom Flannaghan and Tony Yu for adding the
streamplot function.
## Ellipses
In support of the [Phoenix](http://www.jpl.nasa.gov/news/phoenix/main.php)
mission to Mars (which used Matplotlib to display ground tracking of
spacecraft), Michael Droettboom built on work by Charlie Moad to provide
an extremely accurate 8-spline approximation to elliptical arcs (see
[``Arc``](https://matplotlib.org/api/_as_gen/matplotlib.patches.Arc.html#matplotlib.patches.Arc)), which are insensitive to zoom level.
<center>
<a href="/gallery/shapes_and_collections/ellipse_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_ellipse_demo_0011.png">
</a>
<p>
<b>Ellipse Demo</b>
</p>
</center>
## Bar charts
Use the [``bar()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html#matplotlib.pyplot.bar) function to make bar charts, which
includes customizations such as error bars:
<center>
<a href="/gallery/statistics/barchart_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_barchart_demo_0011.png">
</a>
<p>
<b>Barchart Demo</b>
</p>
</center>
You can also create stacked bars
([bar_stacked.py](https://matplotlib.org/gallery/lines_bars_and_markers/bar_stacked.html)),
or horizontal bar charts
([barh.py](https://matplotlib.org/gallery/lines_bars_and_markers/barh.html)).
## Pie charts
The [``pie()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html#matplotlib.pyplot.pie) function allows you to create pie
charts. Optional features include auto-labeling the percentage of area,
exploding one or more wedges from the center of the pie, and a shadow effect.
Take a close look at the attached code, which generates this figure in just
a few lines of code.
<center>
<a href="/gallery/pie_and_polar_charts/pie_features.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_pie_features_0011.png">
</a>
<p>
<b>Pie Features</b>
</p>
</center>
## Tables
The [``table()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.table.html#matplotlib.pyplot.table) function adds a text table
to an axes.
<center>
<a href="/gallery/misc/table_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_table_demo_0011.png">
</a>
<p>
<b>Table Demo</b>
</p>
</center>
## Scatter plots
The [``scatter()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html#matplotlib.pyplot.scatter) function makes a scatter plot
with (optional) size and color arguments. This example plots changes
in Google's stock price, with marker sizes reflecting the
trading volume and colors varying with time. Here, the
alpha attribute is used to make semitransparent circle markers.
<center>
<a href="/gallery/lines_bars_and_markers/scatter_demo2.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_scatter_demo2_0011.png">
</a>
<p>
<b>Scatter Demo2</b>
</p>
</center>
## GUI widgets
Matplotlib has basic GUI widgets that are independent of the graphical
user interface you are using, allowing you to write cross GUI figures
and widgets. See [``matplotlib.widgets``](https://matplotlib.org/api/widgets_api.html#module-matplotlib.widgets) and the
[widget examples](https://matplotlib.org/gallery/index.html).
<center>
<a href="/gallery/widgets/slider_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_slider_demo_0011.png">
</a>
<p>
<b>Slider and radio-button GUI.</b>
</p>
</center>
## Filled curves
The [``fill()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.fill.html#matplotlib.pyplot.fill) function lets you
plot filled curves and polygons:
<center>
<a href="/gallery/lines_bars_and_markers/fill.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_fill_0011.png">
</a>
<p>
<b>Fill</b>
</p>
</center>
Thanks to Andrew Straw for adding this function.
## Date handling
You can plot timeseries data with major and minor ticks and custom
tick formatters for both.
<center>
<a href="/gallery/text_labels_and_annotations/date.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_date_0011.png">
</a>
<p>
<b>Date</b>
</p>
</center>
See [``matplotlib.ticker``](https://matplotlib.org/api/ticker_api.html#module-matplotlib.ticker) and [``matplotlib.dates``](https://matplotlib.org/api/dates_api.html#module-matplotlib.dates) for details and usage.
## Log plots
The [``semilogx()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.semilogx.html#matplotlib.pyplot.semilogx),
[``semilogy()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.semilogy.html#matplotlib.pyplot.semilogy) and
[``loglog()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.loglog.html#matplotlib.pyplot.loglog) functions simplify the creation of
logarithmic plots.
<center>
<a href="/gallery/scales/log_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_log_demo_0011.png">
</a>
<p>
<b>Log Demo</b>
</p>
</center>
Thanks to Andrew Straw, Darren Dale and Gregory Lielens for contributions
log-scaling infrastructure.
## Polar plots
The [``polar()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.polar.html#matplotlib.pyplot.polar) function generates polar plots.
<center>
<a href="/gallery/pie_and_polar_charts/polar_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_polar_demo_0011.png">
</a>
<p>
<b>Polar Demo</b>
</p>
</center>
## Legends
The [``legend()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html#matplotlib.pyplot.legend) function automatically
generates figure legends, with MATLAB-compatible legend-placement
functions.
<center>
<a href="/gallery/text_labels_and_annotations/legend.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_legend_0011.png">
</a>
<p>
<b>Legend</b>
</p>
</center>
Thanks to Charles Twardy for input on the legend function.
## TeX-notation for text objects
Below is a sampling of the many TeX expressions now supported by Matplotlib's
internal mathtext engine. The mathtext module provides TeX style mathematical
expressions using [FreeType](https://www.freetype.org/)
and the DejaVu, BaKoMa computer modern, or [STIX](http://www.stixfonts.org)
fonts. See the [``matplotlib.mathtext``](https://matplotlib.org/api/mathtext_api.html#module-matplotlib.mathtext) module for additional details.
<center>
<a href="/gallery/text_labels_and_annotations/mathtext_examples.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_mathtext_examples_0011.png">
</a>
<p>
<b>Mathtext Examples</b>
</p>
</center>
Matplotlib's mathtext infrastructure is an independent implementation and
does not require TeX or any external packages installed on your computer. See
the tutorial at [Writing mathematical expressions](https://matplotlib.org//text/mathtext.html).
## Native TeX rendering
Although Matplotlib's internal math rendering engine is quite
powerful, sometimes you need TeX. Matplotlib supports external TeX
rendering of strings with the *usetex* option.
<center>
<a href="/gallery/text_labels_and_annotations/tex_demo.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_tex_demo_0011.png">
</a>
<p>
<b>Tex Demo</b>
</p>
</center>
## EEG GUI
You can embed Matplotlib into pygtk, wx, Tk, or Qt applications.
Here is a screenshot of an EEG viewer called [pbrain](https://github.com/nipy/pbrain).
![eeg_small](https://matplotlib.org/_images/eeg_small.png)
The lower axes uses [``specgram()``](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.specgram.html#matplotlib.pyplot.specgram)
to plot the spectrogram of one of the EEG channels.
For examples of how to embed Matplotlib in different toolkits, see:
- [Embedding in GTK3](https://matplotlib.org/gallery/user_interfaces/embedding_in_gtk3_sgskip.html)
- [Embedding in wx #2](https://matplotlib.org/gallery/user_interfaces/embedding_in_wx2_sgskip.html)
- [Matplotlib With Glade 3](https://matplotlib.org/gallery/user_interfaces/mpl_with_glade3_sgskip.html)
- [Embedding in Qt](https://matplotlib.org/gallery/user_interfaces/embedding_in_qt_sgskip.html)
- [Embedding in Tk](https://matplotlib.org/gallery/user_interfaces/embedding_in_tk_sgskip.html)
## XKCD-style sketch plots
Just for fun, Matplotlib supports plotting in the style of ``xkcd``.
<center>
<a href="/gallery/showcase/xkcd.html">
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_xkcd_0011.png">
</a>
<p>
<b>xkcd</b>
</p>
</center>
## Subplot example
Many plot types can be combined in one figure to create
powerful and flexible representations of data.
<center>
<img style="width: 50%" src="https://matplotlib.org/_images/sphx_glr_sample_plots_001.png">
</center>
``` python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
data = np.random.randn(2, 100)
fig, axs = plt.subplots(2, 2, figsize=(5, 5))
axs[0, 0].hist(data[0])
axs[1, 0].scatter(data[0], data[1])
axs[0, 1].plot(data[0], data[1])
axs[1, 1].hist2d(data[0], data[1])
plt.show()
```
## Download
- [Download Python source code: sample_plots.py](https://matplotlib.org/_downloads/6b0f2d1b3dc8d0e75eaa96feb738e947/sample_plots.py)
- [Download Jupyter notebook: sample_plots.ipynb](https://matplotlib.org/_downloads/dcfd63fc031d50e9c085f5dc4aa458b1/sample_plots.ipynb)

View File

@@ -0,0 +1,812 @@
---
sidebarDepth: 3
sidebar: auto
---
# Usage Guide
This tutorial covers some basic usage patterns and best-practices to
help you get started with Matplotlib.
## General Concepts
``matplotlib`` has an extensive codebase that can be daunting to many
new users. However, most of matplotlib can be understood with a fairly
simple conceptual framework and knowledge of a few important points.
Plotting requires action on a range of levels, from the most general
(e.g., 'contour this 2-D array') to the most specific (e.g., 'color
this screen pixel red'). The purpose of a plotting package is to assist
you in visualizing your data as easily as possible, with all the necessary
control -- that is, by using relatively high-level commands most of
the time, and still have the ability to use the low-level commands when
needed.
Therefore, everything in matplotlib is organized in a hierarchy. At the top
of the hierarchy is the matplotlib "state-machine environment" which is
provided by the [``matplotlib.pyplot``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot) module. At this level, simple
functions are used to add plot elements (lines, images, text, etc.) to
the current axes in the current figure.
::: tip Note
Pyplot's state-machine environment behaves similarly to MATLAB and
should be most familiar to users with MATLAB experience.
:::
The next level down in the hierarchy is the first level of the object-oriented
interface, in which pyplot is used only for a few functions such as figure
creation, and the user explicitly creates and keeps track of the figure
and axes objects. At this level, the user uses pyplot to create figures,
and through those figures, one or more axes objects can be created. These
axes objects are then used for most plotting actions.
For even more control -- which is essential for things like embedding
matplotlib plots in GUI applications -- the pyplot level may be dropped
completely, leaving a purely object-oriented approach.
``` python
# sphinx_gallery_thumbnail_number = 3
import matplotlib.pyplot as plt
import numpy as np
```
## Parts of a Figure
![anatomy](https://matplotlib.org/_images/anatomy.png)
### ``Figure``
The **whole** figure. The figure keeps
track of all the child [``Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes), a smattering of
'special' artists (titles, figure legends, etc), and the **canvas**.
(Don't worry too much about the canvas, it is crucial as it is the
object that actually does the drawing to get you your plot, but as the
user it is more-or-less invisible to you). A figure can have any
number of [``Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes), but to be useful should have
at least one.
The easiest way to create a new figure is with pyplot:
``` python
fig = plt.figure() # an empty figure with no axes
fig.suptitle('No axes on this figure') # Add a title so we know which it is
fig, ax_lst = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
```
- ![sphx_glr_usage_001](https://matplotlib.org/_images/sphx_glr_usage_001.png)
- ![sphx_glr_usage_002](https://matplotlib.org/_images/sphx_glr_usage_002.png)
### ``Axes``
This is what you think of as 'a plot', it is the region of the image
with the data space. A given figure
can contain many Axes, but a given [``Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes)
object can only be in one [``Figure``](https://matplotlib.orgapi/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure). The
Axes contains two (or three in the case of 3D)
[``Axis``](https://matplotlib.orgapi/axis_api.html#matplotlib.axis.Axis) objects (be aware of the difference
between **Axes** and **Axis**) which take care of the data limits (the
data limits can also be controlled via set via the
[``set_xlim()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_xlim.html#matplotlib.axes.Axes.set_xlim) and
[``set_ylim()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_ylim.html#matplotlib.axes.Axes.set_ylim) ``Axes`` methods). Each
``Axes`` has a title (set via
[``set_title()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_title.html#matplotlib.axes.Axes.set_title)), an x-label (set via
[``set_xlabel()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_xlabel.html#matplotlib.axes.Axes.set_xlabel)), and a y-label set via
[``set_ylabel()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_ylabel.html#matplotlib.axes.Axes.set_ylabel)).
The ``Axes`` class and its member functions are the primary entry
point to working with the OO interface.
### ``Axis``
These are the number-line-like objects. They take
care of setting the graph limits and generating the ticks (the marks
on the axis) and ticklabels (strings labeling the ticks). The
location of the ticks is determined by a
[``Locator``](https://matplotlib.orgapi/ticker_api.html#matplotlib.ticker.Locator) object and the ticklabel strings
are formatted by a [``Formatter``](https://matplotlib.orgapi/ticker_api.html#matplotlib.ticker.Formatter). The
combination of the correct ``Locator`` and ``Formatter`` gives
very fine control over the tick locations and labels.
### ``Artist``
Basically everything you can see on the figure is an artist (even the
``Figure``, ``Axes``, and ``Axis`` objects). This
includes ``Text`` objects, ``Line2D`` objects,
``collection`` objects, ``Patch`` objects ... (you get the
idea). When the figure is rendered, all of the artists are drawn to
the **canvas**. Most Artists are tied to an Axes; such an Artist
cannot be shared by multiple Axes, or moved from one to another.
## Types of inputs to plotting functions
All of plotting functions expect ``np.array`` or ``np.ma.masked_array`` as
input. Classes that are 'array-like' such as [``pandas``](https://pandas.pydata.org/pandas-docs/stable/index.html#module-pandas) data objects
and ``np.matrix`` may or may not work as intended. It is best to
convert these to ``np.array`` objects prior to plotting.
For example, to convert a [``pandas.DataFrame``](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame)
``` python
a = pandas.DataFrame(np.random.rand(4,5), columns = list('abcde'))
a_asarray = a.values
```
and to convert a ``np.matrix``
``` python
b = np.matrix([[1,2],[3,4]])
b_asarray = np.asarray(b)
```
## Matplotlib, pyplot and pylab: how are they related?
Matplotlib is the whole package and [``matplotlib.pyplot``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot) is a module in
Matplotlib.
For functions in the pyplot module, there is always a "current" figure and
axes (which is created automatically on request). For example, in the
following example, the first call to ``plt.plot`` creates the axes, then
subsequent calls to ``plt.plot`` add additional lines on the same axes, and
``plt.xlabel``, ``plt.ylabel``, ``plt.title`` and ``plt.legend`` set the
axes labels and title and add a legend.
``` python
x = np.linspace(0, 2, 100)
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
plt.show()
```
![sphx_glr_usage_003](https://matplotlib.org/_images/sphx_glr_usage_003.png)
``pylab`` is a convenience module that bulk imports
[``matplotlib.pyplot``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot) (for plotting) and [``numpy``](https://docs.scipy.org/doc/numpy/reference/index.html#module-numpy)
(for mathematics and working with arrays) in a single namespace.
pylab is deprecated and its use is strongly discouraged because
of namespace pollution. Use pyplot instead.
For non-interactive plotting it is suggested
to use pyplot to create the figures and then the OO interface for
plotting.
## Coding Styles
When viewing this documentation and examples, you will find different
coding styles and usage patterns. These styles are perfectly valid
and have their pros and cons. Just about all of the examples can be
converted into another style and achieve the same results.
The only caveat is to avoid mixing the coding styles for your own code.
::: tip Note
Developers for matplotlib have to follow a specific style and guidelines.
See [The Matplotlib Developers' Guide](https://matplotlib.orgdevel/index.html#developers-guide-index).
:::
Of the different styles, there are two that are officially supported.
Therefore, these are the preferred ways to use matplotlib.
For the pyplot style, the imports at the top of your
scripts will typically be:
``` python
import matplotlib.pyplot as plt
import numpy as np
```
Then one calls, for example, np.arange, np.zeros, np.pi, plt.figure,
plt.plot, plt.show, etc. Use the pyplot interface
for creating figures, and then use the object methods for the rest:
``` python
x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
```
![sphx_glr_usage_004](https://matplotlib.org/_images/sphx_glr_usage_004.png)
So, why all the extra typing instead of the MATLAB-style (which relies
on global state and a flat namespace)? For very simple things like
this example, the only advantage is academic: the wordier styles are
more explicit, more clear as to where things come from and what is
going on. For more complicated applications, this explicitness and
clarity becomes increasingly valuable, and the richer and more
complete object-oriented interface will likely make the program easier
to write and maintain.
Typically one finds oneself making the same plots over and over
again, but with different data sets, which leads to needing to write
specialized functions to do the plotting. The recommended function
signature is something like:
``` python
def my_plotter(ax, data1, data2, param_dict):
"""
A helper function to make a graph
Parameters
----------
ax : Axes
The axes to draw to
data1 : array
The x data
data2 : array
The y data
param_dict : dict
Dictionary of kwargs to pass to ax.plot
Returns
-------
out : list
list of artists added
"""
out = ax.plot(data1, data2, **param_dict)
return out
# which you would then use as:
data1, data2, data3, data4 = np.random.randn(4, 100)
fig, ax = plt.subplots(1, 1)
my_plotter(ax, data1, data2, {'marker': 'x'})
```
![sphx_glr_usage_005](https://matplotlib.org/_images/sphx_glr_usage_005.png)
or if you wanted to have 2 sub-plots:
``` python
fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
```
![sphx_glr_usage_006](https://matplotlib.org/_images/sphx_glr_usage_006.png)
Again, for these simple examples this style seems like overkill, however
once the graphs get slightly more complex it pays off.
## Backends
### What is a backend?
A lot of documentation on the website and in the mailing lists refers
to the "backend" and many new users are confused by this term.
matplotlib targets many different use cases and output formats. Some
people use matplotlib interactively from the python shell and have
plotting windows pop up when they type commands. Some people run
[Jupyter](https://jupyter.org) notebooks and draw inline plots for
quick data analysis. Others embed matplotlib into graphical user
interfaces like wxpython or pygtk to build rich applications. Some
people use matplotlib in batch scripts to generate postscript images
from numerical simulations, and still others run web application
servers to dynamically serve up graphs.
To support all of these use cases, matplotlib can target different
outputs, and each of these capabilities is called a backend; the
"frontend" is the user facing code, i.e., the plotting code, whereas the
"backend" does all the hard work behind-the-scenes to make the figure.
There are two types of backends: user interface backends (for use in
pygtk, wxpython, tkinter, qt4, or macosx; also referred to as
"interactive backends") and hardcopy backends to make image files
(PNG, SVG, PDF, PS; also referred to as "non-interactive backends").
There are four ways to configure your backend. If they conflict each other,
the method mentioned last in the following list will be used, e.g. calling
[``use()``](https://matplotlib.orgapi/matplotlib_configuration_api.html#matplotlib.use) will override the setting in your ``matplotlibrc``.
::: tip Note
Backend name specifications are not case-sensitive; e.g., 'GTK3Agg'
and 'gtk3agg' are equivalent.
:::
With a typical installation of matplotlib, such as from a
binary installer or a linux distribution package, a good default
backend will already be set, allowing both interactive work and
plotting from scripts, with output to the screen and/or to
a file, so at least initially you will not need to use any of the
methods given above.
If, however, you want to write graphical user interfaces, or a web
application server ([How to use Matplotlib in a web application server](https://matplotlib.orgfaq/howto_faq.html#howto-webapp)), or need a better
understanding of what is going on, read on. To make things a little
more customizable for graphical user interfaces, matplotlib separates
the concept of the renderer (the thing that actually does the drawing)
from the canvas (the place where the drawing goes). The canonical
renderer for user interfaces is ``Agg`` which uses the [Anti-Grain
Geometry](http://antigrain.com/) C++ library to make a raster (pixel) image of the figure.
All of the user interfaces except ``macosx`` can be used with
agg rendering, e.g., ``WXAgg``, ``GTK3Agg``, ``QT4Agg``, ``QT5Agg``,
``TkAgg``. In addition, some of the user interfaces support other rendering
engines. For example, with GTK+ 3, you can also select Cairo rendering
(backend ``GTK3Cairo``).
For the rendering engines, one can also distinguish between [vector](https://en.wikipedia.org/wiki/Vector_graphics) or [raster](https://en.wikipedia.org/wiki/Raster_graphics) renderers. Vector
graphics languages issue drawing commands like "draw a line from this
point to this point" and hence are scale free, and raster backends
generate a pixel representation of the line whose accuracy depends on a
DPI setting.
Here is a summary of the matplotlib renderers (there is an eponymous
backend for each; these are *non-interactive backends*, capable of
writing to a file):
---
Renderer
Filetypes
Description
[AGG](htt[[ps](https://matplotlib.org/../glossary/index.html#term-ps)](https://matplotlib.org/../glossary/index.html#term-ps)://matplotlib.org/../glossary/index.html#term-agg)
[[png](https://matplotlib.org/../glossary/index.html#term-png)](https://matplotlib.org/../glossary/index.html#term-png)
[[raster graphics](https://matplotlib.org/../glossary/index.html#term-raster-graphics)](https://matplotlib.org/../glossary/index.html#term-raster-graphics) -- high quality images
using the [Anti-Grain Geometry](http://antigrain.com/) engine
PS
ps
[eps](https://matplotlib.org/../glossary/index.html#term-eps)
[[[[vector graphics](https://matplotlib.org/../glossary/index.html#term-vector-graphics)](https://matplotlib.org/../glossary/index.html#term-vector-graphics)](https://matplotlib.org/../glossary/index.html#term-vector-graphics)](https://matplotlib.org/../glossary/index.html#term-vector-graphics) -- [Postscript](https://en.wikipedia.org/wiki/PostScript) output
PDF
[[pdf](https://matplotlib.org/../glossary/index.html#term-pdf)](https://matplotlib.org/../glossary/index.html#term-pdf)
vector graphics --
[Portable Document Format](https://en.wikipedia.org/wiki/Portable_Document_Format)
SVG
[[svg](https://matplotlib.org/../glossary/index.html#term-svg)](https://matplotlib.org/../glossary/index.html#term-svg)
vector graphics --
[Scalable Vector Graphics](https://en.wikipedia.org/wiki/Scalable_Vector_Graphics)
[Cairo](https://matplotlib.org/../glossary/index.html#term-cairo)
png
ps
pdf
svg
raster graphics and
vector graphics -- using the
[Cairo graphics](https://wwW.cairographics.org) library
And here are the user interfaces and renderer combinations supported;
these are *interactive backends*, capable of displaying to the screen
and of using appropriate renderers from the table above to write to
a file:
---
Backend
Description
[Qt5](https://matplotlib.org/../glossary/index.html#term-qt5)Agg
Agg rendering in a Qt5 canvas (requires [PyQt5](https://riverbankcomputing.com/software/pyqt/intro)). This
backend can be activated in IPython with %matplotlib qt5.
ipympl
Agg rendering embedded in a Jupyter widget. (requires ipympl).
This backend can be enabled in a Jupyter notebook with
%matplotlib ipympl.
[[GTK](https://matplotlib.org/../glossary/index.html#term-gtk)](https://matplotlib.org/../glossary/index.html#term-gtk)3Agg
Agg rendering to a GTK 3.x canvas (requires [[PyGObject](https://wiki.gnome.org/action/show/Projects/PyGObject)](https://wiki.gnome.org/action/show/Projects/PyGObject),
and [[pycairo](https://www.cairographics.org/pycairo/)](https://www.cairographics.org/pycairo/) or [[cairocffi](https://pythonhosted.org/cairocffi/)](https://pythonhosted.org/cairocffi/)). This backend can be activated in
IPython with %matplotlib gtk3.
macosx
Agg rendering into a Cocoa canvas in OSX. This backend can be
activated in IPython with %matplotlib osx.
[Tk](https://matplotlib.org/../glossary/index.html#term-tk)Agg
Agg rendering to a Tk canvas (requires [TkInter](https://wiki.python.org/moin/TkInter)). This
backend can be activated in IPython with %matplotlib tk.
nbAgg
Embed an interactive figure in a Jupyter classic notebook. This
backend can be enabled in Jupyter notebooks via
%matplotlib notebook.
WebAgg
On show() will start a tornado server with an interactive
figure.
GTK3Cairo
Cairo rendering to a GTK 3.x canvas (requires PyGObject,
and pycairo or cairocffi).
[Qt4](https://matplotlib.org/../glossary/index.html#term-qt4)Agg
Agg rendering to a Qt4 canvas (requires [PyQt4](https://riverbankcomputing.com/software/pyqt/intro) or
pyside). This backend can be activated in IPython with
%matplotlib qt4.
WXAgg
Agg rendering to a [wxWidgets](https://matplotlib.org/../glossary/index.html#term-wxwidgets) canvas (requires [wxPython](https://www.wxpython.org/) 4).
This backend can be activated in IPython with %matplotlib wx.
### ipympl
The Jupyter widget ecosystem is moving too fast to support directly in
Matplotlib. To install ipympl
``` bash
pip install ipympl
jupyter nbextension enable --py --sys-prefix ipympl
```
or
``` bash
conda install ipympl -c conda-forge
```
See [jupyter-matplotlib](https://github.com/matplotlib/jupyter-matplotlib)
for more details.
### GTK and Cairo
``GTK3`` backends (*both* ``GTK3Agg`` and ``GTK3Cairo``) depend on Cairo
(pycairo>=1.11.0 or cairocffi).
### How do I select PyQt4 or PySide?
The ``QT_API`` environment variable can be set to either ``pyqt`` or ``pyside``
to use ``PyQt4`` or ``PySide``, respectively.
Since the default value for the bindings to be used is ``PyQt4``,
``matplotlib`` first tries to import it, if the import fails, it tries to
import ``PySide``.
## What is interactive mode?
Use of an interactive backend (see [What is a backend?](#what-is-a-backend))
permits--but does not by itself require or ensure--plotting
to the screen. Whether and when plotting to the screen occurs,
and whether a script or shell session continues after a plot
is drawn on the screen, depends on the functions and methods
that are called, and on a state variable that determines whether
matplotlib is in "interactive mode". The default Boolean value is set
by the ``matplotlibrc`` file, and may be customized like any other
configuration parameter (see [Customizing Matplotlib with style sheets and rcParams](customizing.html)). It
may also be set via [``matplotlib.interactive()``](https://matplotlib.orgapi/matplotlib_configuration_api.html#matplotlib.interactive), and its
value may be queried via [``matplotlib.is_interactive()``](https://matplotlib.orgapi/matplotlib_configuration_api.html#matplotlib.is_interactive). Turning
interactive mode on and off in the middle of a stream of plotting
commands, whether in a script or in a shell, is rarely needed
and potentially confusing, so in the following we will assume all
plotting is done with interactive mode either on or off.
::: tip Note
Major changes related to interactivity, and in particular the
role and behavior of [``show()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show), were made in the
transition to matplotlib version 1.0, and bugs were fixed in
1.0.1. Here we describe the version 1.0.1 behavior for the
primary interactive backends, with the partial exception of
*macosx*.
:::
Interactive mode may also be turned on via [``matplotlib.pyplot.ion()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.ion.html#matplotlib.pyplot.ion),
and turned off via [``matplotlib.pyplot.ioff()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.ioff.html#matplotlib.pyplot.ioff).
::: tip Note
Interactive mode works with suitable backends in ipython and in
the ordinary python shell, but it does *not* work in the IDLE IDE.
If the default backend does not support interactivity, an interactive
backend can be explicitly activated using any of the methods discussed in [What is a backend?](#id4).
:::
### Interactive example
From an ordinary python prompt, or after invoking ipython with no options,
try this:
``` python
import matplotlib.pyplot as plt
plt.ion()
plt.plot([1.6, 2.7])
```
Assuming you are running version 1.0.1 or higher, and you have
an interactive backend installed and selected by default, you should
see a plot, and your terminal prompt should also be active; you
can type additional commands such as:
``` python
plt.title("interactive test")
plt.xlabel("index")
```
and you will see the plot being updated after each line. Since version 1.5,
modifying the plot by other means *should* also automatically
update the display on most backends. Get a reference to the [``Axes``](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes) instance,
and call a method of that instance:
``` python
ax = plt.gca()
ax.plot([3.1, 2.2])
```
If you are using certain backends (like ``macosx``), or an older version
of matplotlib, you may not see the new line added to the plot immediately.
In this case, you need to explicitly call [``draw()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.draw.html#matplotlib.pyplot.draw)
in order to update the plot:
``` python
plt.draw()
```
### Non-interactive example
Start a fresh session as in the previous example, but now
turn interactive mode off:
``` python
import matplotlib.pyplot as plt
plt.ioff()
plt.plot([1.6, 2.7])
```
Nothing happened--or at least nothing has shown up on the
screen (unless you are using *macosx* backend, which is
anomalous). To make the plot appear, you need to do this:
``` python
plt.show()
```
Now you see the plot, but your terminal command line is
unresponsive; the ``show()`` command *blocks* the input
of additional commands until you manually kill the plot
window.
What good is this--being forced to use a blocking function?
Suppose you need a script that plots the contents of a file
to the screen. You want to look at that plot, and then end
the script. Without some blocking command such as show(), the
script would flash up the plot and then end immediately,
leaving nothing on the screen.
In addition, non-interactive mode delays all drawing until
show() is called; this is more efficient than redrawing
the plot each time a line in the script adds a new feature.
Prior to version 1.0, show() generally could not be called
more than once in a single script (although sometimes one
could get away with it); for version 1.0.1 and above, this
restriction is lifted, so one can write a script like this:
``` python
import numpy as np
import matplotlib.pyplot as plt
plt.ioff()
for i in range(3):
plt.plot(np.random.rand(10))
plt.show()
```
which makes three plots, one at a time. I.e. the second plot will show up,
once the first plot is closed.
### Summary
In interactive mode, pyplot functions automatically draw
to the screen.
When plotting interactively, if using
object method calls in addition to pyplot functions, then
call [``draw()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.draw.html#matplotlib.pyplot.draw) whenever you want to
refresh the plot.
Use non-interactive mode in scripts in which you want to
generate one or more figures and display them before ending
or generating a new set of figures. In that case, use
[``show()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show) to display the figure(s) and
to block execution until you have manually destroyed them.
## Performance
Whether exploring data in interactive mode or programmatically
saving lots of plots, rendering performance can be a painful
bottleneck in your pipeline. Matplotlib provides a couple
ways to greatly reduce rendering time at the cost of a slight
change (to a settable tolerance) in your plot's appearance.
The methods available to reduce rendering time depend on the
type of plot that is being created.
### Line segment simplification
For plots that have line segments (e.g. typical line plots,
outlines of polygons, etc.), rendering performance can be
controlled by the ``path.simplify`` and
``path.simplify_threshold`` parameters in your
``matplotlibrc`` file (see
[Customizing Matplotlib with style sheets and rcParams](customizing.html) for
more information about the ``matplotlibrc`` file).
The ``path.simplify`` parameter is a boolean indicating whether
or not line segments are simplified at all. The
``path.simplify_threshold`` parameter controls how much line
segments are simplified; higher thresholds result in quicker
rendering.
The following script will first display the data without any
simplification, and then display the same data with simplification.
Try interacting with both of them:
``` python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
# Setup, and create the data to plot
y = np.random.rand(100000)
y[50000:] *= 2
y[np.logspace(1, np.log10(50000), 400).astype(int)] = -1
mpl.rcParams['path.simplify'] = True
mpl.rcParams['path.simplify_threshold'] = 0.0
plt.plot(y)
plt.show()
mpl.rcParams['path.simplify_threshold'] = 1.0
plt.plot(y)
plt.show()
```
Matplotlib currently defaults to a conservative simplification
threshold of ``1/9``. If you want to change your default settings
to use a different value, you can change your ``matplotlibrc``
file. Alternatively, you could create a new style for
interactive plotting (with maximal simplification) and another
style for publication quality plotting (with minimal
simplification) and activate them as necessary. See
[Customizing Matplotlib with style sheets and rcParams](customizing.html) for
instructions on how to perform these actions.
The simplification works by iteratively merging line segments
into a single vector until the next line segment's perpendicular
distance to the vector (measured in display-coordinate space)
is greater than the ``path.simplify_threshold`` parameter.
::: tip Note
Changes related to how line segments are simplified were made
in version 2.1. Rendering time will still be improved by these
parameters prior to 2.1, but rendering time for some kinds of
data will be vastly improved in versions 2.1 and greater.
:::
### Marker simplification
Markers can also be simplified, albeit less robustly than
line segments. Marker simplification is only available
to [``Line2D``](https://matplotlib.orgapi/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D) objects (through the
``markevery`` property). Wherever
[``Line2D``](https://matplotlib.orgapi/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D) construction parameters
are passed through, such as
[``matplotlib.pyplot.plot()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) and
[``matplotlib.axes.Axes.plot()``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot), the ``markevery``
parameter can be used:
``` python
plt.plot(x, y, markevery=10)
```
The markevery argument allows for naive subsampling, or an
attempt at evenly spaced (along the *x* axis) sampling. See the
[Markevery Demo](https://matplotlib.orggallery/lines_bars_and_markers/markevery_demo.html)
for more information.
### Splitting lines into smaller chunks
If you are using the Agg backend (see [What is a backend?](#what-is-a-backend)),
then you can make use of the ``agg.path.chunksize`` rc parameter.
This allows you to specify a chunk size, and any lines with
greater than that many vertices will be split into multiple
lines, each of which has no more than ``agg.path.chunksize``
many vertices. (Unless ``agg.path.chunksize`` is zero, in
which case there is no chunking.) For some kind of data,
chunking the line up into reasonable sizes can greatly
decrease rendering time.
The following script will first display the data without any
chunk size restriction, and then display the same data with
a chunk size of 10,000. The difference can best be seen when
the figures are large, try maximizing the GUI and then
interacting with them:
``` python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['path.simplify_threshold'] = 1.0
# Setup, and create the data to plot
y = np.random.rand(100000)
y[50000:] *= 2
y[np.logspace(1,np.log10(50000), 400).astype(int)] = -1
mpl.rcParams['path.simplify'] = True
mpl.rcParams['agg.path.chunksize'] = 0
plt.plot(y)
plt.show()
mpl.rcParams['agg.path.chunksize'] = 10000
plt.plot(y)
plt.show()
```
### Legends
The default legend behavior for axes attempts to find the location
that covers the fewest data points (``loc='best'``). This can be a
very expensive computation if there are lots of data points. In
this case, you may want to provide a specific location.
### Using the fast style
The *fast* style can be used to automatically set
simplification and chunking parameters to reasonable
settings to speed up plotting large amounts of data.
It can be used simply by running:
``` python
import matplotlib.style as mplstyle
mplstyle.use('fast')
```
It is very light weight, so it plays nicely with other
styles, just make sure the fast style is applied last
so that other styles do not overwrite the settings:
``` python
mplstyle.use(['dark_background', 'ggplot', 'fast'])
```
## Download
- [Download Python source code: usage.py](https://matplotlib.org/_downloads/841a514c2538fd0de68b22f22b25f56d/usage.py)
- [Download Jupyter notebook: usage.ipynb](https://matplotlib.org/_downloads/16d604c55fb650c0dce205aa67def02b/usage.ipynb)