mirror of
https://github.com/Estom/notes.git
synced 2026-02-03 18:44:19 +08:00
matplotlib & pandas
This commit is contained in:
580
Python/matplotlab/text/annotations.md
Normal file
580
Python/matplotlab/text/annotations.md
Normal file
@@ -0,0 +1,580 @@
|
||||
---
|
||||
sidebarDepth: 3
|
||||
sidebar: auto
|
||||
---
|
||||
|
||||
# Annotations
|
||||
|
||||
Annotating text with Matplotlib.
|
||||
|
||||
Table of Contents
|
||||
|
||||
- [Annotations](#annotations)
|
||||
- [Basic annotation](#basic-annotation)
|
||||
- [Advanced Annotation](#advanced-annotation)
|
||||
[Annotating with Text with Box](#annotating-with-text-with-box)
|
||||
[Annotating with Arrow](#annotating-with-arrow)
|
||||
[Placing Artist at the anchored location of the Axes](#placing-artist-at-the-anchored-location-of-the-axes)
|
||||
[Using Complex Coordinates with Annotations](#using-complex-coordinates-with-annotations)
|
||||
[Using ConnectionPatch](#using-connectionpatch)
|
||||
[Advanced Topics](#advanced-topics)
|
||||
|
||||
|
||||
[Zoom effect between Axes](#zoom-effect-between-axes)
|
||||
[Define Custom BoxStyle](#define-custom-boxstyle)
|
||||
- [Annotating with Text with Box](#annotating-with-text-with-box)
|
||||
- [Annotating with Arrow](#annotating-with-arrow)
|
||||
- [Placing Artist at the anchored location of the Axes](#placing-artist-at-the-anchored-location-of-the-axes)
|
||||
- [Using Complex Coordinates with Annotations](#using-complex-coordinates-with-annotations)
|
||||
- [Using ConnectionPatch](#using-connectionpatch)
|
||||
[Advanced Topics](#advanced-topics)
|
||||
- [Advanced Topics](#advanced-topics)
|
||||
- [Zoom effect between Axes](#zoom-effect-between-axes)
|
||||
- [Define Custom BoxStyle](#define-custom-boxstyle)
|
||||
# Basic annotation
|
||||
|
||||
The uses of the basic [``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text) will place text
|
||||
at an arbitrary position on the Axes. A common use case of text is to
|
||||
annotate some feature of the plot, and the
|
||||
``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.
|
||||
|
||||
Annotation Basic
|
||||
|
||||
In this 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 -- you can specify the coordinate
|
||||
system of ``xy`` and ``xytext`` with one of the following strings for
|
||||
``xycoords`` and ``textcoords`` (default is 'data')
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
argument
|
||||
coordinate system
|
||||
|
||||
|
||||
|
||||
'figure points'
|
||||
points from the lower left corner of the figure
|
||||
|
||||
'figure pixels'
|
||||
pixels from the lower left corner of the figure
|
||||
|
||||
'figure fraction'
|
||||
0,0 is lower left of figure and 1,1 is upper right
|
||||
|
||||
'axes points'
|
||||
points from lower left corner of axes
|
||||
|
||||
'axes pixels'
|
||||
pixels from lower left corner of axes
|
||||
|
||||
'axes fraction'
|
||||
0,0 is lower left of axes and 1,1 is upper right
|
||||
|
||||
'data'
|
||||
use the axes data coordinate system
|
||||
|
||||
|
||||
|
||||
|
||||
For example to place the text coordinates in fractional axes
|
||||
coordinates, one could do:
|
||||
|
||||
``` python
|
||||
ax.annotate('local max', xy=(3, 1), xycoords='data',
|
||||
xytext=(0.8, 0.95), textcoords='axes fraction',
|
||||
arrowprops=dict(facecolor='black', shrink=0.05),
|
||||
horizontalalignment='right', verticalalignment='top',
|
||||
)
|
||||
```
|
||||
|
||||
For physical coordinate systems (points or pixels) the origin is the
|
||||
bottom-left of the figure or axes.
|
||||
|
||||
Optionally, you can enable drawing of an arrow from the text to the annotated
|
||||
point by giving a dictionary of arrow properties in the optional keyword
|
||||
argument ``arrowprops``.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
arrowprops key
|
||||
description
|
||||
|
||||
|
||||
|
||||
width
|
||||
the width of the arrow in points
|
||||
|
||||
frac
|
||||
the fraction of the arrow length occupied by the head
|
||||
|
||||
headwidth
|
||||
the width of the base of the arrow head in points
|
||||
|
||||
shrink
|
||||
move the tip and base some percent away from
|
||||
the annotated point and text
|
||||
|
||||
**kwargs
|
||||
any key for [matplotlib.patches.Polygon](https://matplotlib.org/../api/_as_gen/matplotlib.patches.Polygon.html#matplotlib.patches.Polygon),
|
||||
e.g., facecolor
|
||||
|
||||
|
||||
|
||||
|
||||
In the example below, the ``xy`` point is in native coordinates
|
||||
(``xycoords`` defaults to 'data'). For a polar axes, this is in
|
||||
(theta, radius) space. The text in this example is placed in the
|
||||
fractional figure coordinate system. [``matplotlib.text.Text``](https://matplotlib.orgapi/text_api.html#matplotlib.text.Text)
|
||||
keyword args like ``horizontalalignment``, ``verticalalignment`` and
|
||||
``fontsize`` are passed from ``annotate`` to the
|
||||
``Text`` instance.
|
||||
|
||||
Annotation Polar
|
||||
|
||||
For more on all the wild and wonderful things you can do with
|
||||
annotations, including fancy arrows, see [Advanced Annotation](#plotting-guide-annotation)
|
||||
and [Annotating Plots](https://matplotlib.orggallery/text_labels_and_annotations/annotation_demo.html).
|
||||
|
||||
Do not proceed unless you have already read [Basic annotation](#annotations-tutorial),
|
||||
[``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text) and [``annotate()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.annotate.html#matplotlib.pyplot.annotate)!
|
||||
# Advanced Annotation
|
||||
|
||||
## Annotating with Text with Box
|
||||
|
||||
Let's start with a simple example.
|
||||
|
||||
Annotate Text Arrow
|
||||
|
||||
The [``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text) function in the pyplot module (or
|
||||
text method of the Axes class) takes bbox keyword argument, and when
|
||||
given, a box around the text is drawn.
|
||||
|
||||
``` python
|
||||
bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2)
|
||||
t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45,
|
||||
size=15,
|
||||
bbox=bbox_props)
|
||||
```
|
||||
|
||||
The patch object associated with the text can be accessed by:
|
||||
|
||||
``` python
|
||||
bb = t.get_bbox_patch()
|
||||
```
|
||||
|
||||
The return value is an instance of FancyBboxPatch and the patch
|
||||
properties like facecolor, edgewidth, etc. can be accessed and
|
||||
modified as usual. To change the shape of the box, use the *set_boxstyle*
|
||||
method.
|
||||
|
||||
``` python
|
||||
bb.set_boxstyle("rarrow", pad=0.6)
|
||||
```
|
||||
|
||||
The arguments are the name of the box style with its attributes as
|
||||
keyword arguments. Currently, following box styles are implemented.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Class
|
||||
Name
|
||||
Attrs
|
||||
|
||||
|
||||
|
||||
Circle
|
||||
circle
|
||||
pad=0.3
|
||||
|
||||
DArrow
|
||||
darrow
|
||||
pad=0.3
|
||||
|
||||
LArrow
|
||||
larrow
|
||||
pad=0.3
|
||||
|
||||
RArrow
|
||||
rarrow
|
||||
pad=0.3
|
||||
|
||||
Round
|
||||
round
|
||||
pad=0.3,rounding_size=None
|
||||
|
||||
Round4
|
||||
round4
|
||||
pad=0.3,rounding_size=None
|
||||
|
||||
Roundtooth
|
||||
roundtooth
|
||||
pad=0.3,tooth_size=None
|
||||
|
||||
Sawtooth
|
||||
sawtooth
|
||||
pad=0.3,tooth_size=None
|
||||
|
||||
Square
|
||||
square
|
||||
pad=0.3
|
||||
|
||||
|
||||
|
||||
|
||||
Fancybox Demo
|
||||
|
||||
Note that the attribute arguments can be specified within the style
|
||||
name with separating comma (this form can be used as "boxstyle" value
|
||||
of bbox argument when initializing the text instance)
|
||||
|
||||
``` python
|
||||
bb.set_boxstyle("rarrow,pad=0.6")
|
||||
```
|
||||
|
||||
## Annotating with Arrow
|
||||
|
||||
The [``annotate()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.annotate.html#matplotlib.pyplot.annotate) function in the pyplot module
|
||||
(or annotate method of the Axes class) is used to draw an arrow
|
||||
connecting two points on the plot.
|
||||
|
||||
``` python
|
||||
ax.annotate("Annotation",
|
||||
xy=(x1, y1), xycoords='data',
|
||||
xytext=(x2, y2), textcoords='offset points',
|
||||
)
|
||||
```
|
||||
|
||||
This annotates a point at ``xy`` in the given coordinate (``xycoords``)
|
||||
with the text at ``xytext`` given in ``textcoords``. Often, the
|
||||
annotated point is specified in the *data* coordinate and the annotating
|
||||
text in *offset points*.
|
||||
See [``annotate()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.annotate.html#matplotlib.pyplot.annotate) for available coordinate systems.
|
||||
|
||||
An arrow connecting two points (xy & xytext) can be optionally drawn by
|
||||
specifying the ``arrowprops`` argument. To draw only an arrow, use
|
||||
empty string as the first argument.
|
||||
|
||||
``` python
|
||||
ax.annotate("",
|
||||
xy=(0.2, 0.2), xycoords='data',
|
||||
xytext=(0.8, 0.8), textcoords='data',
|
||||
arrowprops=dict(arrowstyle="->",
|
||||
connectionstyle="arc3"),
|
||||
)
|
||||
```
|
||||
|
||||
Annotate Simple01
|
||||
|
||||
The arrow drawing takes a few steps.
|
||||
|
||||
1. a connecting path between two points are created. This is
|
||||
controlled by ``connectionstyle`` key value.
|
||||
1. If patch object is given (*patchA* & *patchB*), the path is clipped to
|
||||
avoid the patch.
|
||||
1. The path is further shrunk by given amount of pixels (*shrinkA*
|
||||
& *shrinkB*)
|
||||
1. The path is transmuted to arrow patch, which is controlled by the
|
||||
``arrowstyle`` key value.
|
||||
|
||||
Annotate Explain
|
||||
|
||||
The creation of the connecting path between two points is controlled by
|
||||
``connectionstyle`` key and the following styles are available.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Name
|
||||
Attrs
|
||||
|
||||
|
||||
|
||||
angle
|
||||
angleA=90,angleB=0,rad=0.0
|
||||
|
||||
angle3
|
||||
angleA=90,angleB=0
|
||||
|
||||
arc
|
||||
angleA=0,angleB=0,armA=None,armB=None,rad=0.0
|
||||
|
||||
arc3
|
||||
rad=0.0
|
||||
|
||||
bar
|
||||
armA=0.0,armB=0.0,fraction=0.3,angle=None
|
||||
|
||||
|
||||
|
||||
|
||||
Note that "3" in ``angle3`` and ``arc3`` is meant to indicate that the
|
||||
resulting path is a quadratic spline segment (three control
|
||||
points). As will be discussed below, some arrow style options can only
|
||||
be used when the connecting path is a quadratic spline.
|
||||
|
||||
The behavior of each connection style is (limitedly) demonstrated in the
|
||||
example below. (Warning : The behavior of the ``bar`` style is currently not
|
||||
well defined, it may be changed in the future).
|
||||
|
||||
Connectionstyle Demo
|
||||
|
||||
The connecting path (after clipping and shrinking) is then mutated to
|
||||
an arrow patch, according to the given ``arrowstyle``.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Name
|
||||
Attrs
|
||||
|
||||
|
||||
|
||||
-
|
||||
None
|
||||
|
||||
->
|
||||
head_length=0.4,head_width=0.2
|
||||
|
||||
-[
|
||||
widthB=1.0,lengthB=0.2,angleB=None
|
||||
|
||||
|-|
|
||||
widthA=1.0,widthB=1.0
|
||||
|
||||
-|>
|
||||
head_length=0.4,head_width=0.2
|
||||
|
||||
<-
|
||||
head_length=0.4,head_width=0.2
|
||||
|
||||
<->
|
||||
head_length=0.4,head_width=0.2
|
||||
|
||||
<|-
|
||||
head_length=0.4,head_width=0.2
|
||||
|
||||
<|-|>
|
||||
head_length=0.4,head_width=0.2
|
||||
|
||||
fancy
|
||||
head_length=0.4,head_width=0.4,tail_width=0.4
|
||||
|
||||
simple
|
||||
head_length=0.5,head_width=0.5,tail_width=0.2
|
||||
|
||||
wedge
|
||||
tail_width=0.3,shrink_factor=0.5
|
||||
|
||||
|
||||
|
||||
|
||||
Fancyarrow Demo
|
||||
|
||||
Some arrowstyles only work with connection styles that generate a
|
||||
quadratic-spline segment. They are ``fancy``, ``simple``, and ``wedge``.
|
||||
For these arrow styles, you must use the "angle3" or "arc3" connection
|
||||
style.
|
||||
|
||||
If the annotation string is given, the patchA is set to the bbox patch
|
||||
of the text by default.
|
||||
|
||||
Annotate Simple02
|
||||
|
||||
As in the text command, a box around the text can be drawn using
|
||||
the ``bbox`` argument.
|
||||
|
||||
Annotate Simple03
|
||||
|
||||
By default, the starting point is set to the center of the text
|
||||
extent. This can be adjusted with ``relpos`` key value. The values
|
||||
are normalized to the extent of the text. For example, (0,0) means
|
||||
lower-left corner and (1,1) means top-right.
|
||||
|
||||
Annotate Simple04
|
||||
|
||||
## Placing Artist at the anchored location of the Axes
|
||||
|
||||
There are classes of artists that can be placed at an anchored location
|
||||
in the Axes. A common example is the legend. This type of artist can
|
||||
be created by using the OffsetBox class. A few predefined classes are
|
||||
available in ``mpl_toolkits.axes_grid1.anchored_artists`` others in
|
||||
``matplotlib.offsetbox``
|
||||
|
||||
``` python
|
||||
from matplotlib.offsetbox import AnchoredText
|
||||
at = AnchoredText("Figure 1a",
|
||||
prop=dict(size=15), frameon=True,
|
||||
loc='upper left',
|
||||
)
|
||||
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
|
||||
ax.add_artist(at)
|
||||
```
|
||||
|
||||
Anchored Box01
|
||||
|
||||
The *loc* keyword has same meaning as in the legend command.
|
||||
|
||||
A simple application is when the size of the artist (or collection of
|
||||
artists) is known in pixel size during the time of creation. For
|
||||
example, If you want to draw a circle with fixed size of 20 pixel x 20
|
||||
pixel (radius = 10 pixel), you can utilize
|
||||
``AnchoredDrawingArea``. The instance is created with a size of the
|
||||
drawing area (in pixels), and arbitrary artists can added to the
|
||||
drawing area. Note that the extents of the artists that are added to
|
||||
the drawing area are not related to the placement of the drawing
|
||||
area itself. Only the initial size matters.
|
||||
|
||||
``` python
|
||||
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
|
||||
|
||||
ada = AnchoredDrawingArea(20, 20, 0, 0,
|
||||
loc='upper right', pad=0., frameon=False)
|
||||
p1 = Circle((10, 10), 10)
|
||||
ada.drawing_area.add_artist(p1)
|
||||
p2 = Circle((30, 10), 5, fc="r")
|
||||
ada.drawing_area.add_artist(p2)
|
||||
```
|
||||
|
||||
The artists that are added to the drawing area should not have a
|
||||
transform set (it will be overridden) and the dimensions of those
|
||||
artists are interpreted as a pixel coordinate, i.e., the radius of the
|
||||
circles in above example are 10 pixels and 5 pixels, respectively.
|
||||
|
||||
Anchored Box02
|
||||
|
||||
Sometimes, you want your artists to scale with the data coordinate (or
|
||||
coordinates other than canvas pixels). You can use
|
||||
``AnchoredAuxTransformBox`` class. This is similar to
|
||||
``AnchoredDrawingArea`` except that the extent of the artist is
|
||||
determined during the drawing time respecting the specified transform.
|
||||
|
||||
``` python
|
||||
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox
|
||||
|
||||
box = AnchoredAuxTransformBox(ax.transData, loc='upper left')
|
||||
el = Ellipse((0,0), width=0.1, height=0.4, angle=30) # in data coordinates!
|
||||
box.drawing_area.add_artist(el)
|
||||
```
|
||||
|
||||
The ellipse in the above example will have width and height
|
||||
corresponding to 0.1 and 0.4 in data coordinates and will be
|
||||
automatically scaled when the view limits of the axes change.
|
||||
|
||||
Anchored Box03
|
||||
|
||||
As in the legend, the bbox_to_anchor argument can be set. Using the
|
||||
HPacker and VPacker, you can have an arrangement(?) of artist as in the
|
||||
legend (as a matter of fact, this is how the legend is created).
|
||||
|
||||
Anchored Box04
|
||||
|
||||
Note that unlike the legend, the ``bbox_transform`` is set
|
||||
to IdentityTransform by default.
|
||||
|
||||
## Using Complex Coordinates with Annotations
|
||||
|
||||
The Annotation in matplotlib supports several types of coordinates as
|
||||
described in [Basic annotation](#annotations-tutorial). For an advanced user who wants
|
||||
more control, it supports a few other options.
|
||||
|
||||
## Using ConnectionPatch
|
||||
|
||||
The ConnectionPatch is like an annotation without text. While the annotate
|
||||
function is recommended in most situations, the ConnectionPatch is useful when
|
||||
you want to connect points in different axes.
|
||||
|
||||
``` python
|
||||
from matplotlib.patches import ConnectionPatch
|
||||
xy = (0.2, 0.2)
|
||||
con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data",
|
||||
axesA=ax1, axesB=ax2)
|
||||
ax2.add_artist(con)
|
||||
```
|
||||
|
||||
The above code connects point xy in the data coordinates of ``ax1`` to
|
||||
point xy in the data coordinates of ``ax2``. Here is a simple example.
|
||||
|
||||
Connect Simple01
|
||||
|
||||
While the ConnectionPatch instance can be added to any axes, you may want to add
|
||||
it to the axes that is latest in drawing order to prevent overlap by other
|
||||
axes.
|
||||
|
||||
### Advanced Topics
|
||||
|
||||
## Zoom effect between Axes
|
||||
|
||||
``mpl_toolkits.axes_grid1.inset_locator`` defines some patch classes useful
|
||||
for interconnecting two axes. Understanding the code requires some
|
||||
knowledge of how mpl's transform works. But, utilizing it will be
|
||||
straight forward.
|
||||
|
||||
Axes Zoom Effect
|
||||
|
||||
## Define Custom BoxStyle
|
||||
|
||||
You can use a custom box style. The value for the ``boxstyle`` can be a
|
||||
callable object in the following forms.:
|
||||
|
||||
``` python
|
||||
def __call__(self, x0, y0, width, height, mutation_size,
|
||||
aspect_ratio=1.):
|
||||
'''
|
||||
Given the location and size of the box, return the path of
|
||||
the box around it.
|
||||
|
||||
- *x0*, *y0*, *width*, *height* : location and size of the box
|
||||
- *mutation_size* : a reference scale for the mutation.
|
||||
- *aspect_ratio* : aspect-ratio for the mutation.
|
||||
'''
|
||||
path = ...
|
||||
return path
|
||||
```
|
||||
|
||||
Here is a complete example.
|
||||
|
||||
Custom Boxstyle01
|
||||
|
||||
However, it is recommended that you derive from the
|
||||
matplotlib.patches.BoxStyle._Base as demonstrated below.
|
||||
|
||||
Custom Boxstyle02
|
||||
|
||||
Similarly, you can define a custom ConnectionStyle and a custom ArrowStyle.
|
||||
See the source code of ``lib/matplotlib/patches.py`` and check
|
||||
how each style class is defined.
|
||||
|
||||
## Download
|
||||
|
||||
- [Download Python source code: annotations.py](https://matplotlib.org/_downloads/e9b9ec3e7de47d2ccae486e437e86de2/annotations.py)
|
||||
- [Download Jupyter notebook: annotations.ipynb](https://matplotlib.org/_downloads/c4f2a18ccd63dc25619141aee3712b03/annotations.ipynb)
|
||||
|
||||
1186
Python/matplotlab/text/mathtext.md
Normal file
1186
Python/matplotlab/text/mathtext.md
Normal file
File diff suppressed because it is too large
Load Diff
260
Python/matplotlab/text/pgf.md
Normal file
260
Python/matplotlab/text/pgf.md
Normal file
@@ -0,0 +1,260 @@
|
||||
---
|
||||
sidebarDepth: 3
|
||||
sidebar: auto
|
||||
---
|
||||
|
||||
# Typesetting With XeLaTeX/LuaLaTeX
|
||||
|
||||
How to typeset text with the ``pgf`` backend in Matplotlib.
|
||||
|
||||
Using the ``pgf`` backend, matplotlib can export figures as pgf drawing commands
|
||||
that can be processed with pdflatex, xelatex or lualatex. XeLaTeX and LuaLaTeX
|
||||
have full unicode support and can use any font that is installed in the operating
|
||||
system, making use of advanced typographic features of OpenType, AAT and
|
||||
Graphite. Pgf pictures created by ``plt.savefig('figure.pgf')`` can be
|
||||
embedded as raw commands in LaTeX documents. Figures can also be directly
|
||||
compiled and saved to PDF with ``plt.savefig('figure.pdf')`` by either
|
||||
switching to the backend
|
||||
|
||||
``` python
|
||||
matplotlib.use('pgf')
|
||||
```
|
||||
|
||||
or registering it for handling pdf output
|
||||
|
||||
``` python
|
||||
from matplotlib.backends.backend_pgf import FigureCanvasPgf
|
||||
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
|
||||
```
|
||||
|
||||
The second method allows you to keep using regular interactive backends and to
|
||||
save xelatex, lualatex or pdflatex compiled PDF files from the graphical user interface.
|
||||
|
||||
Matplotlib's pgf support requires a recent [LaTeX](http://www.tug.org) installation that includes
|
||||
the TikZ/PGF packages (such as [TeXLive](http://www.tug.org/texlive/)), preferably with XeLaTeX or LuaLaTeX
|
||||
installed. If either pdftocairo or ghostscript is present on your system,
|
||||
figures can optionally be saved to PNG images as well. The executables
|
||||
for all applications must be located on your [``PATH``](https://matplotlib.orgfaq/environment_variables_faq.html#envvar-PATH).
|
||||
|
||||
Rc parameters that control the behavior of the pgf backend:
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Parameter
|
||||
Documentation
|
||||
|
||||
|
||||
|
||||
pgf.preamble
|
||||
Lines to be included in the LaTeX preamble
|
||||
|
||||
pgf.rcfonts
|
||||
Setup fonts from rc params using the fontspec package
|
||||
|
||||
pgf.texsystem
|
||||
Either "xelatex" (default), "lualatex" or "pdflatex"
|
||||
|
||||
|
||||
|
||||
|
||||
::: tip Note
|
||||
|
||||
TeX defines a set of special characters, such as:
|
||||
|
||||
``` python
|
||||
# $ % & ~ _ ^ \ { }
|
||||
```
|
||||
|
||||
Generally, these characters must be escaped correctly. For convenience,
|
||||
some characters (_,^,%) are automatically escaped outside of math
|
||||
environments.
|
||||
|
||||
:::
|
||||
|
||||
## Multi-Page PDF Files
|
||||
|
||||
The pgf backend also supports multipage pdf files using ``PdfPages``
|
||||
|
||||
``` python
|
||||
from matplotlib.backends.backend_pgf import PdfPages
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
with PdfPages('multipage.pdf', metadata={'author': 'Me'}) as pdf:
|
||||
|
||||
fig1, ax1 = plt.subplots()
|
||||
ax1.plot([1, 5, 3])
|
||||
pdf.savefig(fig1)
|
||||
|
||||
fig2, ax2 = plt.subplots()
|
||||
ax2.plot([1, 5, 3])
|
||||
pdf.savefig(fig2)
|
||||
```
|
||||
|
||||
## Font specification
|
||||
|
||||
The fonts used for obtaining the size of text elements or when compiling
|
||||
figures to PDF are usually defined in the matplotlib rc parameters. You can
|
||||
also use the LaTeX default Computer Modern fonts by clearing the lists for
|
||||
``font.serif``, ``font.sans-serif`` or ``font.monospace``. Please note that
|
||||
the glyph coverage of these fonts is very limited. If you want to keep the
|
||||
Computer Modern font face but require extended unicode support, consider
|
||||
installing the [Computer Modern Unicode](https://sourceforge.net/projects/cm-unicode/)
|
||||
fonts *CMU Serif*, *CMU Sans Serif*, etc.
|
||||
|
||||
When saving to ``.pgf``, the font configuration matplotlib used for the
|
||||
layout of the figure is included in the header of the text file.
|
||||
|
||||
``` python
|
||||
"""
|
||||
=========
|
||||
Pgf Fonts
|
||||
=========
|
||||
|
||||
"""
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
plt.rcParams.update({
|
||||
"font.family": "serif",
|
||||
"font.serif": [], # use latex default serif font
|
||||
"font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font
|
||||
})
|
||||
|
||||
plt.figure(figsize=(4.5, 2.5))
|
||||
plt.plot(range(5))
|
||||
plt.text(0.5, 3., "serif")
|
||||
plt.text(0.5, 2., "monospace", family="monospace")
|
||||
plt.text(2.5, 2., "sans-serif", family="sans-serif")
|
||||
plt.text(2.5, 1., "comic sans", family="Comic Sans MS")
|
||||
plt.xlabel("µ is not $\\mu$")
|
||||
plt.tight_layout(.5)
|
||||
```
|
||||
|
||||
## Custom preamble
|
||||
|
||||
Full customization is possible by adding your own commands to the preamble.
|
||||
Use the ``pgf.preamble`` parameter if you want to configure the math fonts,
|
||||
using ``unicode-math`` for example, or for loading additional packages. Also,
|
||||
if you want to do the font configuration yourself instead of using the fonts
|
||||
specified in the rc parameters, make sure to disable ``pgf.rcfonts``.
|
||||
|
||||
``` python
|
||||
"""
|
||||
============
|
||||
Pgf Preamble
|
||||
============
|
||||
|
||||
"""
|
||||
|
||||
import matplotlib as mpl
|
||||
mpl.use("pgf")
|
||||
import matplotlib.pyplot as plt
|
||||
plt.rcParams.update({
|
||||
"font.family": "serif", # use serif/main font for text elements
|
||||
"text.usetex": True, # use inline math for ticks
|
||||
"pgf.rcfonts": False, # don't setup fonts from rc parameters
|
||||
"pgf.preamble": [
|
||||
"\\usepackage{units}", # load additional packages
|
||||
"\\usepackage{metalogo}",
|
||||
"\\usepackage{unicode-math}", # unicode math setup
|
||||
r"\setmathfont{xits-math.otf}",
|
||||
r"\setmainfont{DejaVu Serif}", # serif font via preamble
|
||||
]
|
||||
})
|
||||
|
||||
plt.figure(figsize=(4.5, 2.5))
|
||||
plt.plot(range(5))
|
||||
plt.xlabel("unicode text: я, ψ, €, ü, \\unitfrac[10]{°}{µm}")
|
||||
plt.ylabel("\\XeLaTeX")
|
||||
plt.legend(["unicode math: $λ=∑_i^∞ μ_i^2$"])
|
||||
plt.tight_layout(.5)
|
||||
```
|
||||
|
||||
## Choosing the TeX system
|
||||
|
||||
The TeX system to be used by matplotlib is chosen by the ``pgf.texsystem``
|
||||
parameter. Possible values are ``'xelatex'`` (default), ``'lualatex'`` and
|
||||
``'pdflatex'``. Please note that when selecting pdflatex the fonts and
|
||||
unicode handling must be configured in the preamble.
|
||||
|
||||
``` python
|
||||
"""
|
||||
=============
|
||||
Pgf Texsystem
|
||||
=============
|
||||
|
||||
"""
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
plt.rcParams.update({
|
||||
"pgf.texsystem": "pdflatex",
|
||||
"pgf.preamble": [
|
||||
r"\usepackage[utf8x]{inputenc}",
|
||||
r"\usepackage[T1]{fontenc}",
|
||||
r"\usepackage{cmbright}",
|
||||
]
|
||||
})
|
||||
|
||||
plt.figure(figsize=(4.5, 2.5))
|
||||
plt.plot(range(5))
|
||||
plt.text(0.5, 3., "serif", family="serif")
|
||||
plt.text(0.5, 2., "monospace", family="monospace")
|
||||
plt.text(2.5, 2., "sans-serif", family="sans-serif")
|
||||
plt.xlabel(r"µ is not $\mu$")
|
||||
plt.tight_layout(.5)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Please note that the TeX packages found in some Linux distributions and
|
||||
MiKTeX installations are dramatically outdated. Make sure to update your
|
||||
package catalog and upgrade or install a recent TeX distribution.
|
||||
- On Windows, the [``PATH``](https://matplotlib.orgfaq/environment_variables_faq.html#envvar-PATH) environment variable may need to be modified
|
||||
to include the directories containing the latex, dvipng and ghostscript
|
||||
executables. See [Environment Variables](https://matplotlib.orgfaq/environment_variables_faq.html#environment-variables) and
|
||||
[Setting environment variables in windows](https://matplotlib.orgfaq/environment_variables_faq.html#setting-windows-environment-variables) for details.
|
||||
- A limitation on Windows causes the backend to keep file handles that have
|
||||
been opened by your application open. As a result, it may not be possible
|
||||
to delete the corresponding files until the application closes (see
|
||||
[#1324](https://github.com/matplotlib/matplotlib/issues/1324)).
|
||||
- Sometimes the font rendering in figures that are saved to png images is
|
||||
very bad. This happens when the pdftocairo tool is not available and
|
||||
ghostscript is used for the pdf to png conversion.
|
||||
- Make sure what you are trying to do is possible in a LaTeX document,
|
||||
that your LaTeX syntax is valid and that you are using raw strings
|
||||
if necessary to avoid unintended escape sequences.
|
||||
- The ``pgf.preamble`` rc setting provides lots of flexibility, and lots of
|
||||
ways to cause problems. When experiencing problems, try to minimalize or
|
||||
disable the custom preamble.
|
||||
- Configuring an ``unicode-math`` environment can be a bit tricky. The
|
||||
TeXLive distribution for example provides a set of math fonts which are
|
||||
usually not installed system-wide. XeTeX, unlike LuaLatex, cannot find
|
||||
these fonts by their name, which is why you might have to specify
|
||||
``\setmathfont{xits-math.otf}`` instead of ``\setmathfont{XITS Math}`` or
|
||||
alternatively make the fonts available to your OS. See this
|
||||
[tex.stackexchange.com question](http://tex.stackexchange.com/questions/43642)
|
||||
for more details.
|
||||
- If the font configuration used by matplotlib differs from the font setting
|
||||
in yout LaTeX document, the alignment of text elements in imported figures
|
||||
may be off. Check the header of your ``.pgf`` file if you are unsure about
|
||||
the fonts matplotlib used for the layout.
|
||||
- Vector images and hence ``.pgf`` files can become bloated if there are a lot
|
||||
of objects in the graph. This can be the case for image processing or very
|
||||
big scatter graphs. In an extreme case this can cause TeX to run out of
|
||||
memory: "TeX capacity exceeded, sorry" You can configure latex to increase
|
||||
the amount of memory available to generate the ``.pdf`` image as discussed on
|
||||
[tex.stackexchange.com](http://tex.stackexchange.com/questions/7953).
|
||||
Another way would be to "rasterize" parts of the graph causing problems
|
||||
using either the ``rasterized=True`` keyword, or ``.set_rasterized(True)`` as per
|
||||
[this example](https://matplotlib.orggallery/misc/rasterization_demo.html).
|
||||
- If you still need help, please see [Getting help](https://matplotlib.orgfaq/troubleshooting_faq.html#reporting-problems)
|
||||
|
||||
## Download
|
||||
|
||||
- [Download Python source code: pgf.py](https://matplotlib.org/_downloads/33c57cdb935b0436624e8a3471dedc5e/pgf.py)
|
||||
- [Download Jupyter notebook: pgf.ipynb](https://matplotlib.org/_downloads/216a4d9bdb6721e8ad7fda0b85a793ae/pgf.ipynb)
|
||||
|
||||
494
Python/matplotlab/text/text_intro.md
Normal file
494
Python/matplotlab/text/text_intro.md
Normal file
@@ -0,0 +1,494 @@
|
||||
---
|
||||
sidebarDepth: 3
|
||||
sidebar: auto
|
||||
---
|
||||
|
||||
# Text in Matplotlib Plots
|
||||
|
||||
Introduction to plotting and working with text in Matplotlib.
|
||||
|
||||
Matplotlib has extensive text support, including support for
|
||||
mathematical expressions, truetype support for raster and
|
||||
vector outputs, newline separated text with arbitrary
|
||||
rotations, and unicode support.
|
||||
|
||||
Because it embeds fonts directly in output documents, e.g., for postscript
|
||||
or PDF, what you see on the screen is what you get in the hardcopy.
|
||||
[FreeType](https://www.freetype.org/) support
|
||||
produces very nice, antialiased fonts, that look good even at small
|
||||
raster sizes. Matplotlib includes its own
|
||||
[``matplotlib.font_manager``](https://matplotlib.orgapi/font_manager_api.html#module-matplotlib.font_manager) (thanks to Paul Barrett), which
|
||||
implements a cross platform, ``W3C``
|
||||
compliant font finding algorithm.
|
||||
|
||||
The user has a great deal of control over text properties (font size, font
|
||||
weight, text location and color, etc.) with sensible defaults set in
|
||||
the [rc file](https://matplotlib.org/introductory/customizing.html).
|
||||
And significantly, for those interested in mathematical
|
||||
or scientific figures, Matplotlib implements a large number of TeX
|
||||
math symbols and commands, supporting [mathematical expressions](mathtext.html) anywhere in your figure.
|
||||
|
||||
## Basic text commands
|
||||
|
||||
The following commands are used to create text in the pyplot
|
||||
interface and the object-oriented API:
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
[pyplot](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot) API
|
||||
OO API
|
||||
description
|
||||
|
||||
|
||||
|
||||
[[[text](https://matplotlib.org/../api/_as_gen/matplotlib.figure.[[Figure](https://matplotlib.org/../api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure)](https://matplotlib.org/../api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure).html#matplotlib.figure.Figure.text)](https://matplotlib.org/../api/_as_gen/matplotlib.axes.[[[[[Axes](https://matplotlib.org/../api/axes_api.html#matplotlib.axes.Axes)](https://matplotlib.org/../api/axes_api.html#matplotlib.axes.Axes)](https://matplotlib.org/../api/axes_api.html#matplotlib.axes.Axes)](https://matplotlib.org/../api/axes_api.html#matplotlib.axes.Axes)](https://matplotlib.org/../api/axes_api.html#matplotlib.axes.Axes).text.html#matplotlib.axes.Axes.text)](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text)
|
||||
text
|
||||
Add text at an arbitrary location of
|
||||
the Axes.
|
||||
|
||||
[[annotate](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.annotate.html#matplotlib.axes.Axes.annotate)](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.annotate.html#matplotlib.pyplot.annotate)
|
||||
annotate
|
||||
Add an annotation, with an optional
|
||||
arrow, at an arbitrary location of the
|
||||
Axes.
|
||||
|
||||
[xlabel](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.xlabel.html#matplotlib.pyplot.xlabel)
|
||||
[set_xlabel](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.set_xlabel.html#matplotlib.axes.Axes.set_xlabel)
|
||||
Add a label to the
|
||||
Axes's x-axis.
|
||||
|
||||
[ylabel](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.ylabel.html#matplotlib.pyplot.ylabel)
|
||||
[set_ylabel](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.set_ylabel.html#matplotlib.axes.Axes.set_ylabel)
|
||||
Add a label to the
|
||||
Axes's y-axis.
|
||||
|
||||
[title](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.title.html#matplotlib.pyplot.title)
|
||||
[set_title](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.set_title.html#matplotlib.axes.Axes.set_title)
|
||||
Add a title to the
|
||||
Axes.
|
||||
|
||||
[figtext](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.figtext.html#matplotlib.pyplot.figtext)
|
||||
text
|
||||
Add text at an arbitrary location of
|
||||
the Figure.
|
||||
|
||||
[[suptitle](https://matplotlib.org/../api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.suptitle)](https://matplotlib.org/../api/_as_gen/matplotlib.pyplot.suptitle.html#matplotlib.pyplot.suptitle)
|
||||
suptitle
|
||||
Add a title to the Figure.
|
||||
|
||||
|
||||
|
||||
|
||||
All of these functions create and return a [``Text``](https://matplotlib.orgapi/text_api.html#matplotlib.text.Text) instance, which can be
|
||||
configured with a variety of font and other properties. The example below
|
||||
shows all of these commands in action, and more detail is provided in the
|
||||
sections that follow.
|
||||
|
||||
``` python
|
||||
import matplotlib
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fig = plt.figure()
|
||||
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
|
||||
|
||||
ax = fig.add_subplot(111)
|
||||
fig.subplots_adjust(top=0.85)
|
||||
ax.set_title('axes title')
|
||||
|
||||
ax.set_xlabel('xlabel')
|
||||
ax.set_ylabel('ylabel')
|
||||
|
||||
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
|
||||
bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
|
||||
|
||||
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
|
||||
|
||||
ax.text(3, 2, 'unicode: Institut für Festkörperphysik')
|
||||
|
||||
ax.text(0.95, 0.01, 'colored text in axes coords',
|
||||
verticalalignment='bottom', horizontalalignment='right',
|
||||
transform=ax.transAxes,
|
||||
color='green', fontsize=15)
|
||||
|
||||
|
||||
ax.plot([2], [1], 'o')
|
||||
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
|
||||
arrowprops=dict(facecolor='black', shrink=0.05))
|
||||
|
||||
ax.axis([0, 10, 0, 10])
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Labels for x- and y-axis
|
||||
|
||||
Specifying the labels for the x- and y-axis is straightforward, via the
|
||||
[``set_xlabel``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_xlabel.html#matplotlib.axes.Axes.set_xlabel) and [``set_ylabel``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_ylabel.html#matplotlib.axes.Axes.set_ylabel)
|
||||
methods.
|
||||
|
||||
``` python
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
x1 = np.linspace(0.0, 5.0, 100)
|
||||
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
|
||||
|
||||
fig, ax = plt.subplots(figsize=(5, 3))
|
||||
fig.subplots_adjust(bottom=0.15, left=0.2)
|
||||
ax.plot(x1, y1)
|
||||
ax.set_xlabel('time [s]')
|
||||
ax.set_ylabel('Damped oscillation [V]')
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
The x- and y-labels are automatically placed so that they clear the x- and
|
||||
y-ticklabels. Compare the plot below with that above, and note the y-label
|
||||
is to the left of the one above.
|
||||
|
||||
``` python
|
||||
fig, ax = plt.subplots(figsize=(5, 3))
|
||||
fig.subplots_adjust(bottom=0.15, left=0.2)
|
||||
ax.plot(x1, y1*10000)
|
||||
ax.set_xlabel('time [s]')
|
||||
ax.set_ylabel('Damped oscillation [V]')
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
If you want to move the labels, you can specify the *labelpad* keyword
|
||||
argument, where the value is points (1/72", the same unit used to specify
|
||||
fontsizes).
|
||||
|
||||
``` python
|
||||
fig, ax = plt.subplots(figsize=(5, 3))
|
||||
fig.subplots_adjust(bottom=0.15, left=0.2)
|
||||
ax.plot(x1, y1*10000)
|
||||
ax.set_xlabel('time [s]')
|
||||
ax.set_ylabel('Damped oscillation [V]', labelpad=18)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
Or, the labels accept all the [``Text``](https://matplotlib.orgapi/text_api.html#matplotlib.text.Text) keyword arguments, including
|
||||
*position*, via which we can manually specify the label positions. Here we
|
||||
put the xlabel to the far left of the axis. Note, that the y-coordinate of
|
||||
this position has no effect - to adjust the y-position we need to use the
|
||||
*labelpad* kwarg.
|
||||
|
||||
``` python
|
||||
fig, ax = plt.subplots(figsize=(5, 3))
|
||||
fig.subplots_adjust(bottom=0.15, left=0.2)
|
||||
ax.plot(x1, y1)
|
||||
ax.set_xlabel('time [s]', position=(0., 1e6),
|
||||
horizontalalignment='left')
|
||||
ax.set_ylabel('Damped oscillation [V]')
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
All the labelling in this tutorial can be changed by manipulating the
|
||||
[``matplotlib.font_manager.FontProperties``](https://matplotlib.orgapi/font_manager_api.html#matplotlib.font_manager.FontProperties) method, or by named kwargs to
|
||||
[``set_xlabel``](https://matplotlib.orgapi/_as_gen/matplotlib.axes.Axes.set_xlabel.html#matplotlib.axes.Axes.set_xlabel)
|
||||
|
||||
``` python
|
||||
from matplotlib.font_manager import FontProperties
|
||||
|
||||
font = FontProperties()
|
||||
font.set_family('serif')
|
||||
font.set_name('Times New Roman')
|
||||
font.set_style('italic')
|
||||
|
||||
fig, ax = plt.subplots(figsize=(5, 3))
|
||||
fig.subplots_adjust(bottom=0.15, left=0.2)
|
||||
ax.plot(x1, y1)
|
||||
ax.set_xlabel('time [s]', fontsize='large', fontweight='bold')
|
||||
ax.set_ylabel('Damped oscillation [V]', fontproperties=font)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
Finally, we can use native TeX rendering in all text objects and have
|
||||
multiple lines:
|
||||
|
||||
``` python
|
||||
fig, ax = plt.subplots(figsize=(5, 3))
|
||||
fig.subplots_adjust(bottom=0.2, left=0.2)
|
||||
ax.plot(x1, np.cumsum(y1**2))
|
||||
ax.set_xlabel('time [s] \n This was a long experiment')
|
||||
ax.set_ylabel(r'$\int\ Y^2\ dt\ \ [V^2 s]$')
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Titles
|
||||
|
||||
Subplot titles are set in much the same way as labels, but there is
|
||||
the *loc* keyword arguments that can change the position and justification
|
||||
from the default value of ``loc=center``.
|
||||
|
||||
``` python
|
||||
fig, axs = plt.subplots(3, 1, figsize=(5, 6), tight_layout=True)
|
||||
locs = ['center', 'left', 'right']
|
||||
for ax, loc in zip(axs, locs):
|
||||
ax.plot(x1, y1)
|
||||
ax.set_title('Title with loc at '+loc, loc=loc)
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
Vertical spacing for titles is controlled via ``rcParams["axes.titlepad"] = 6.0``, which
|
||||
defaults to 5 points. Setting to a different value moves the title.
|
||||
|
||||
``` python
|
||||
fig, ax = plt.subplots(figsize=(5, 3))
|
||||
fig.subplots_adjust(top=0.8)
|
||||
ax.plot(x1, y1)
|
||||
ax.set_title('Vertically offset title', pad=30)
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Ticks and ticklabels
|
||||
|
||||
Placing ticks and ticklabels is a very tricky aspect of making a figure.
|
||||
Matplotlib does the best it can automatically, but it also offers a very
|
||||
flexible framework for determining the choices for tick locations, and
|
||||
how they are labelled.
|
||||
|
||||
### Terminology
|
||||
|
||||
*Axes* have an [``matplotlib.axis``](https://matplotlib.orgapi/axis_api.html#module-matplotlib.axis) object for the ``ax.xaxis``
|
||||
and ``ax.yaxis`` that
|
||||
contain the information about how the labels in the axis are laid out.
|
||||
|
||||
The axis API is explained in detail in the documentation to
|
||||
[``axis``](https://matplotlib.orgapi/axis_api.html#module-matplotlib.axis).
|
||||
|
||||
An Axis object has major and minor ticks. The Axis has a
|
||||
``matplotlib.xaxis.set_major_locator`` and
|
||||
``matplotlib.xaxis.set_minor_locator`` methods that use the data being plotted
|
||||
to determine
|
||||
the location of major and minor ticks. There are also
|
||||
``matplotlib.xaxis.set_major_formatter`` and
|
||||
``matplotlib.xaxis.set_minor_formatters`` methods that format the tick labels.
|
||||
|
||||
### Simple ticks
|
||||
|
||||
It often is convenient to simply define the
|
||||
tick values, and sometimes the tick labels, overriding the default
|
||||
locators and formatters. This is discouraged because it breaks itneractive
|
||||
navigation of the plot. It also can reset the axis limits: note that
|
||||
the second plot has the ticks we asked for, including ones that are
|
||||
well outside the automatic view limits.
|
||||
|
||||
``` python
|
||||
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
|
||||
axs[0].plot(x1, y1)
|
||||
axs[1].plot(x1, y1)
|
||||
axs[1].xaxis.set_ticks(np.arange(0., 8.1, 2.))
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
We can of course fix this after the fact, but it does highlight a
|
||||
weakness of hard-coding the ticks. This example also changes the format
|
||||
of the ticks:
|
||||
|
||||
``` python
|
||||
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
|
||||
axs[0].plot(x1, y1)
|
||||
axs[1].plot(x1, y1)
|
||||
ticks = np.arange(0., 8.1, 2.)
|
||||
# list comprehension to get all tick labels...
|
||||
tickla = ['%1.2f' % tick for tick in ticks]
|
||||
axs[1].xaxis.set_ticks(ticks)
|
||||
axs[1].xaxis.set_ticklabels(tickla)
|
||||
axs[1].set_xlim(axs[0].get_xlim())
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
### Tick Locators and Formatters
|
||||
|
||||
Instead of making a list of all the tickalbels, we could have
|
||||
used a [``matplotlib.ticker.FormatStrFormatter``](https://matplotlib.orgapi/ticker_api.html#matplotlib.ticker.FormatStrFormatter) and passed it to the
|
||||
``ax.xaxis``
|
||||
|
||||
``` python
|
||||
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
|
||||
axs[0].plot(x1, y1)
|
||||
axs[1].plot(x1, y1)
|
||||
ticks = np.arange(0., 8.1, 2.)
|
||||
# list comprehension to get all tick labels...
|
||||
formatter = matplotlib.ticker.StrMethodFormatter('{x:1.1f}')
|
||||
axs[1].xaxis.set_ticks(ticks)
|
||||
axs[1].xaxis.set_major_formatter(formatter)
|
||||
axs[1].set_xlim(axs[0].get_xlim())
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
And of course we could have used a non-default locator to set the
|
||||
tick locations. Note we still pass in the tick values, but the
|
||||
x-limit fix used above is *not* needed.
|
||||
|
||||
``` python
|
||||
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
|
||||
axs[0].plot(x1, y1)
|
||||
axs[1].plot(x1, y1)
|
||||
formatter = matplotlib.ticker.FormatStrFormatter('%1.1f')
|
||||
locator = matplotlib.ticker.FixedLocator(ticks)
|
||||
axs[1].xaxis.set_major_locator(locator)
|
||||
axs[1].xaxis.set_major_formatter(formatter)
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
The default formatter is the [``matplotlib.ticker.MaxNLocator``](https://matplotlib.orgapi/ticker_api.html#matplotlib.ticker.MaxNLocator) called as
|
||||
``ticker.MaxNLocator(self, nbins='auto', steps=[1, 2, 2.5, 5, 10])``
|
||||
The *steps* keyword contains a list of multiples that can be used for
|
||||
tick values. i.e. in this case, 2, 4, 6 would be acceptable ticks,
|
||||
as would 20, 40, 60 or 0.2, 0.4, 0.6. However, 3, 6, 9 would not be
|
||||
acceptable because 3 doesn't appear in the list of steps.
|
||||
|
||||
``nbins=auto`` uses an algorithm to determine how many ticks will
|
||||
be acceptable based on how long the axis is. The fontsize of the
|
||||
ticklabel is taken into account, but the length of the tick string
|
||||
is not (because its not yet known.) In the bottom row, the
|
||||
ticklabels are quite large, so we set ``nbins=4`` to make the
|
||||
labels fit in the right-hand plot.
|
||||
|
||||
``` python
|
||||
fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
|
||||
for n, ax in enumerate(axs.flat):
|
||||
ax.plot(x1*10., y1)
|
||||
|
||||
formatter = matplotlib.ticker.FormatStrFormatter('%1.1f')
|
||||
locator = matplotlib.ticker.MaxNLocator(nbins='auto', steps=[1, 4, 10])
|
||||
axs[0, 1].xaxis.set_major_locator(locator)
|
||||
axs[0, 1].xaxis.set_major_formatter(formatter)
|
||||
|
||||
formatter = matplotlib.ticker.FormatStrFormatter('%1.5f')
|
||||
locator = matplotlib.ticker.AutoLocator()
|
||||
axs[1, 0].xaxis.set_major_formatter(formatter)
|
||||
axs[1, 0].xaxis.set_major_locator(locator)
|
||||
|
||||
formatter = matplotlib.ticker.FormatStrFormatter('%1.5f')
|
||||
locator = matplotlib.ticker.MaxNLocator(nbins=4)
|
||||
axs[1, 1].xaxis.set_major_formatter(formatter)
|
||||
axs[1, 1].xaxis.set_major_locator(locator)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
Finally, we can specify functions for the formatter using
|
||||
[``matplotlib.ticker.FuncFormatter``](https://matplotlib.orgapi/ticker_api.html#matplotlib.ticker.FuncFormatter).
|
||||
|
||||
``` python
|
||||
def formatoddticks(x, pos):
|
||||
"""Format odd tick positions
|
||||
"""
|
||||
if x % 2:
|
||||
return '%1.2f' % x
|
||||
else:
|
||||
return ''
|
||||
|
||||
fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
|
||||
ax.plot(x1, y1)
|
||||
formatter = matplotlib.ticker.FuncFormatter(formatoddticks)
|
||||
locator = matplotlib.ticker.MaxNLocator(nbins=6)
|
||||
ax.xaxis.set_major_formatter(formatter)
|
||||
ax.xaxis.set_major_locator(locator)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
### Dateticks
|
||||
|
||||
Matplotlib can accept [``datetime.datetime``](https://docs.python.org/3/library/datetime.html#datetime.datetime) and ``numpy.datetime64``
|
||||
objects as plotting arguments. Dates and times require special
|
||||
formatting, which can often benefit from manual intervention. In
|
||||
order to help, dates have special Locators and Formatters,
|
||||
defined in the [``matplotlib.dates``](https://matplotlib.orgapi/dates_api.html#module-matplotlib.dates) module.
|
||||
|
||||
A simple example is as follows. Note how we have to rotate the
|
||||
tick labels so that they don't over-run each other.
|
||||
|
||||
``` python
|
||||
import datetime
|
||||
|
||||
fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
|
||||
base = datetime.datetime(2017, 1, 1, 0, 0, 1)
|
||||
time = [base + datetime.timedelta(days=x) for x in range(len(y1))]
|
||||
|
||||
ax.plot(time, y1)
|
||||
ax.tick_params(axis='x', rotation=70)
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
We can pass a format
|
||||
to [``matplotlib.dates.DateFormatter``](https://matplotlib.orgapi/dates_api.html#matplotlib.dates.DateFormatter). Also note that the 29th and the
|
||||
next month are very close together. We can fix this by using the
|
||||
``dates.DayLocator`` class, which allows us to specify a list of days of the
|
||||
month to use. Similar formatters are listed in the [``matplotlib.dates``](https://matplotlib.orgapi/dates_api.html#module-matplotlib.dates) module.
|
||||
|
||||
``` python
|
||||
import matplotlib.dates as mdates
|
||||
|
||||
locator = mdates.DayLocator(bymonthday=[1, 15])
|
||||
formatter = mdates.DateFormatter('%b %d')
|
||||
|
||||
fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
|
||||
ax.xaxis.set_major_locator(locator)
|
||||
ax.xaxis.set_major_formatter(formatter)
|
||||
ax.plot(time, y1)
|
||||
ax.tick_params(axis='x', rotation=70)
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Legends and Annotations
|
||||
|
||||
- Legends: [Legend guide](https://matplotlib.org/intermediate/legend_guide.html)
|
||||
- Annotations: [Annotations](annotations.html)
|
||||
|
||||
**Total running time of the script:** ( 0 minutes 2.549 seconds)
|
||||
|
||||
## Download
|
||||
|
||||
- [Download Python source code: text_intro.py](https://matplotlib.org/_downloads/8eeacd0a48953caa8d20de07b4c4ef50/text_intro.py)
|
||||
- [Download Jupyter notebook: text_intro.ipynb](https://matplotlib.org/_downloads/b1f39cf888a0a639ac54bae2e28dfe44/text_intro.ipynb)
|
||||
|
||||
336
Python/matplotlab/text/text_props.md
Normal file
336
Python/matplotlab/text/text_props.md
Normal file
@@ -0,0 +1,336 @@
|
||||
---
|
||||
sidebarDepth: 3
|
||||
sidebar: auto
|
||||
---
|
||||
|
||||
# Text properties and layout
|
||||
|
||||
Controlling properties of text and its layout with Matplotlib.
|
||||
|
||||
The [``matplotlib.text.Text``](https://matplotlib.orgapi/text_api.html#matplotlib.text.Text) instances have a variety of
|
||||
properties which can be configured via keyword arguments to the text
|
||||
commands (e.g., [``title()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.title.html#matplotlib.pyplot.title),
|
||||
[``xlabel()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.xlabel.html#matplotlib.pyplot.xlabel) and [``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text)).
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Property
|
||||
Value Type
|
||||
|
||||
|
||||
|
||||
alpha
|
||||
[[[[float](https://pillow.readthedocs.io/en/stable/reference/ImageMath.html#float)](https://pillow.readthedocs.io/en/stable/reference/ImageMath.html#float)](https://pillow.readthedocs.io/en/stable/reference/ImageMath.html#float)](https://pillow.readthedocs.io/en/stable/reference/ImageMath.html#float)
|
||||
|
||||
background[[color](https://matplotlib.org/colors/colors.html)](https://matplotlib.org/colors/colors.html)
|
||||
any matplotlib color
|
||||
|
||||
bbox
|
||||
[Rectangle](https://matplotlib.org/../api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle) prop dict plus key 'pad' which is a pad in points
|
||||
|
||||
clip_box
|
||||
a matplotlib.transform.Bbox instance
|
||||
|
||||
clip_on
|
||||
bool
|
||||
|
||||
clip_path
|
||||
a [Path](https://matplotlib.org/../api/path_api.html#matplotlib.path.Path) instance and a [[Transform](https://matplotlib.org/../api/transformations.html#matplotlib.transforms.Transform)](https://matplotlib.org/../api/transformations.html#matplotlib.transforms.Transform) instance, a [Patch](https://matplotlib.org/../api/_as_gen/matplotlib.patches.Patch.html#matplotlib.patches.Patch)
|
||||
|
||||
color
|
||||
any matplotlib color
|
||||
|
||||
family
|
||||
[ 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ]
|
||||
|
||||
fontproperties
|
||||
a [FontProperties](https://matplotlib.org/../api/font_manager_api.html#matplotlib.font_manager.FontProperties) instance
|
||||
|
||||
horizontalalignment or ha
|
||||
[ 'center' | 'right' | 'left' ]
|
||||
|
||||
label
|
||||
any string
|
||||
|
||||
linespacing
|
||||
float
|
||||
|
||||
multialignment
|
||||
['left' | 'right' | 'center' ]
|
||||
|
||||
name or fontname
|
||||
string e.g., ['Sans' | 'Courier' | 'Helvetica' ...]
|
||||
|
||||
picker
|
||||
[None|float|boolean|callable]
|
||||
|
||||
position
|
||||
(x, y)
|
||||
|
||||
rotation
|
||||
[ angle in degrees | 'vertical' | 'horizontal' ]
|
||||
|
||||
size or fontsize
|
||||
[ size in points | relative size, e.g., 'smaller', 'x-large' ]
|
||||
|
||||
style or fontstyle
|
||||
[ 'normal' | 'italic' | 'oblique' ]
|
||||
|
||||
text
|
||||
string or anything printable with '%s' conversion
|
||||
|
||||
transform
|
||||
a Transform instance
|
||||
|
||||
variant
|
||||
[ 'normal' | 'small-caps' ]
|
||||
|
||||
verticalalignment or va
|
||||
[ 'center' | 'top' | 'bottom' | 'baseline' ]
|
||||
|
||||
visible
|
||||
bool
|
||||
|
||||
weight or fontweight
|
||||
[ 'normal' | 'bold' | 'heavy' | 'light' | 'ultrabold' | 'ultralight']
|
||||
|
||||
x
|
||||
float
|
||||
|
||||
y
|
||||
float
|
||||
|
||||
zorder
|
||||
any number
|
||||
|
||||
|
||||
|
||||
|
||||
You can lay out text with the alignment arguments
|
||||
``horizontalalignment``, ``verticalalignment``, and
|
||||
``multialignment``. ``horizontalalignment`` controls whether the x
|
||||
positional argument for the text indicates the left, center or right
|
||||
side of the text bounding box. ``verticalalignment`` controls whether
|
||||
the y positional argument for the text indicates the bottom, center or
|
||||
top side of the text bounding box. ``multialignment``, for newline
|
||||
separated strings only, controls whether the different lines are left,
|
||||
center or right justified. Here is an example which uses the
|
||||
[``text()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text) command to show the various alignment
|
||||
possibilities. The use of ``transform=ax.transAxes`` throughout the
|
||||
code indicates that the coordinates are given relative to the axes
|
||||
bounding box, with 0,0 being the lower left of the axes and 1,1 the
|
||||
upper right.
|
||||
|
||||
``` python
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.patches as patches
|
||||
|
||||
# build a rectangle in axes coords
|
||||
left, width = .25, .5
|
||||
bottom, height = .25, .5
|
||||
right = left + width
|
||||
top = bottom + height
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_axes([0, 0, 1, 1])
|
||||
|
||||
# axes coordinates are 0,0 is bottom left and 1,1 is upper right
|
||||
p = patches.Rectangle(
|
||||
(left, bottom), width, height,
|
||||
fill=False, transform=ax.transAxes, clip_on=False
|
||||
)
|
||||
|
||||
ax.add_patch(p)
|
||||
|
||||
ax.text(left, bottom, 'left top',
|
||||
horizontalalignment='left',
|
||||
verticalalignment='top',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(left, bottom, 'left bottom',
|
||||
horizontalalignment='left',
|
||||
verticalalignment='bottom',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(right, top, 'right bottom',
|
||||
horizontalalignment='right',
|
||||
verticalalignment='bottom',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(right, top, 'right top',
|
||||
horizontalalignment='right',
|
||||
verticalalignment='top',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(right, bottom, 'center top',
|
||||
horizontalalignment='center',
|
||||
verticalalignment='top',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(left, 0.5*(bottom+top), 'right center',
|
||||
horizontalalignment='right',
|
||||
verticalalignment='center',
|
||||
rotation='vertical',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(left, 0.5*(bottom+top), 'left center',
|
||||
horizontalalignment='left',
|
||||
verticalalignment='center',
|
||||
rotation='vertical',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',
|
||||
horizontalalignment='center',
|
||||
verticalalignment='center',
|
||||
fontsize=20, color='red',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(right, 0.5*(bottom+top), 'centered',
|
||||
horizontalalignment='center',
|
||||
verticalalignment='center',
|
||||
rotation='vertical',
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.text(left, top, 'rotated\nwith newlines',
|
||||
horizontalalignment='center',
|
||||
verticalalignment='center',
|
||||
rotation=45,
|
||||
transform=ax.transAxes)
|
||||
|
||||
ax.set_axis_off()
|
||||
plt.show()
|
||||
```
|
||||
|
||||

|
||||
# Default Font
|
||||
|
||||
The base default font is controlled by a set of rcParams. To set the font
|
||||
for mathematical expressions, use the rcParams beginning with ``mathtext``
|
||||
(see [mathtext](mathtext.html#mathtext-fonts)).
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
rcParam
|
||||
usage
|
||||
|
||||
|
||||
|
||||
'font.family'
|
||||
List of either names of font or {'cursive',
|
||||
'fantasy', 'monospace', 'sans', 'sans serif',
|
||||
'sans-serif', 'serif'}.
|
||||
|
||||
'font.style'
|
||||
The default style, ex 'normal',
|
||||
'italic'.
|
||||
|
||||
'font.variant'
|
||||
Default variant, ex 'normal', 'small-caps'
|
||||
(untested)
|
||||
|
||||
'font.stretch'
|
||||
Default stretch, ex 'normal', 'condensed'
|
||||
(incomplete)
|
||||
|
||||
'font.weight'
|
||||
Default weight. Either string or integer
|
||||
|
||||
'font.size'
|
||||
Default font size in points. Relative font sizes
|
||||
('large', 'x-small') are computed against
|
||||
this size.
|
||||
|
||||
|
||||
|
||||
|
||||
The mapping between the family aliases (``{'cursive', 'fantasy',
|
||||
'monospace', 'sans', 'sans serif', 'sans-serif', 'serif'}``) and actual font names
|
||||
is controlled by the following rcParams:
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
family alias
|
||||
rcParam with mappings
|
||||
|
||||
|
||||
|
||||
'serif'
|
||||
'font.serif'
|
||||
|
||||
'monospace'
|
||||
'font.monospace'
|
||||
|
||||
'fantasy'
|
||||
'font.fantasy'
|
||||
|
||||
'cursive'
|
||||
'font.cursive'
|
||||
|
||||
{'sans', 'sans serif', 'sans-serif'}
|
||||
'font.sans-serif'
|
||||
|
||||
|
||||
|
||||
|
||||
which are lists of font names.
|
||||
|
||||
## Text with non-latin glyphs
|
||||
|
||||
As of v2.0 the [default font](https://matplotlib.orgusers/dflt_style_changes.html#default-changes-font) contains
|
||||
glyphs for many western alphabets, but still does not cover all of the
|
||||
glyphs that may be required by mpl users. For example, DejaVu has no
|
||||
coverage of Chinese, Korean, or Japanese.
|
||||
|
||||
To set the default font to be one that supports the code points you
|
||||
need, prepend the font name to ``'font.family'`` or the desired alias
|
||||
lists
|
||||
|
||||
``` python
|
||||
matplotlib.rcParams['font.sans-serif'] = ['Source Han Sans TW', 'sans-serif']
|
||||
```
|
||||
|
||||
or set it in your ``.matplotlibrc`` file:
|
||||
|
||||
``` python
|
||||
font.sans-serif: Source Han Sans TW, Arial, sans-serif
|
||||
```
|
||||
|
||||
To control the font used on per-artist basis use the ``'name'``,
|
||||
``'fontname'`` or ``'fontproperties'`` kwargs documented [above](#).
|
||||
|
||||
On linux, [fc-list](https://linux.die.net/man/1/fc-list) can be a
|
||||
useful tool to discover the font name; for example
|
||||
|
||||
``` python
|
||||
$ fc-list :lang=zh family
|
||||
Noto to Sans Mono CJK TC,Noto Sans Mono CJK TC Bold
|
||||
Noto Sans CJK TC,Noto Sans CJK TC Medium
|
||||
Noto Sans CJK TC,Noto Sans CJK TC DemiLight
|
||||
Noto Sans CJK KR,Noto Sans CJK KR Black
|
||||
Noto Sans CJK TC,Noto Sans CJK TC Black
|
||||
Noto Sans Mono CJK TC,Noto Sans Mono CJK TC Regular
|
||||
Noto Sans CJK SC,Noto Sans CJK SC Light
|
||||
```
|
||||
|
||||
lists all of the fonts that support Chinese.
|
||||
|
||||
## Download
|
||||
|
||||
- [Download Python source code: text_props.py](https://matplotlib.org/_downloads/ae6077d9637819ed9799d96f3fccde64/text_props.py)
|
||||
- [Download Jupyter notebook: text_props.ipynb](https://matplotlib.org/_downloads/a34bdc8d86b130a33d92221e0c320b5b/text_props.ipynb)
|
||||
|
||||
144
Python/matplotlab/text/usetex.md
Normal file
144
Python/matplotlab/text/usetex.md
Normal file
@@ -0,0 +1,144 @@
|
||||
---
|
||||
sidebarDepth: 3
|
||||
sidebar: auto
|
||||
---
|
||||
|
||||
# Text rendering With LaTeX
|
||||
|
||||
Rendering text with LaTeX in Matplotlib.
|
||||
|
||||
Matplotlib has the option to use LaTeX to manage all text layout. This
|
||||
option is available with the following backends:
|
||||
|
||||
- Agg
|
||||
- PS
|
||||
- PDF
|
||||
|
||||
The LaTeX option is activated by setting ``text.usetex : True`` in your rc
|
||||
settings. Text handling with matplotlib's LaTeX support is slower than
|
||||
matplotlib's very capable [mathtext](mathtext.html), but is
|
||||
more flexible, since different LaTeX packages (font packages, math packages,
|
||||
etc.) can be used. The results can be striking, especially when you take care
|
||||
to use the same fonts in your figures as in the main document.
|
||||
|
||||
Matplotlib's LaTeX support requires a working [LaTeX](http://www.tug.org) installation, [dvipng](http://www.nongnu.org/dvipng/)
|
||||
(which may be included with your LaTeX installation), and [Ghostscript](https://ghostscript.com/)
|
||||
(GPL Ghostscript 9.0 or later is required). The executables for these
|
||||
external dependencies must all be located on your [``PATH``](https://matplotlib.orgfaq/environment_variables_faq.html#envvar-PATH).
|
||||
|
||||
There are a couple of options to mention, which can be changed using
|
||||
[rc settings](https://matplotlib.org/introductory/customizing.html). Here is an example
|
||||
matplotlibrc file:
|
||||
|
||||
``` python
|
||||
font.family : serif
|
||||
font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman
|
||||
font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans serif
|
||||
font.cursive : Zapf Chancery
|
||||
font.monospace : Courier, Computer Modern Typewriter
|
||||
|
||||
text.usetex : true
|
||||
```
|
||||
|
||||
The first valid font in each family is the one that will be loaded. If the
|
||||
fonts are not specified, the Computer Modern fonts are used by default. All of
|
||||
the other fonts are Adobe fonts. Times and Palatino each have their own
|
||||
accompanying math fonts, while the other Adobe serif fonts make use of the
|
||||
Computer Modern math fonts. See the [PSNFSS](http://www.ctan.org/tex-archive/macros/latex/required/psnfss/psnfss2e.pdf) documentation for more details.
|
||||
|
||||
To use LaTeX and select Helvetica as the default font, without editing
|
||||
matplotlibrc use:
|
||||
|
||||
``` python
|
||||
from matplotlib import rc
|
||||
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
|
||||
## for Palatino and other serif fonts use:
|
||||
#rc('font',**{'family':'serif','serif':['Palatino']})
|
||||
rc('text', usetex=True)
|
||||
```
|
||||
|
||||
Here is the standard example, ``tex_demo.py``:
|
||||
|
||||
TeX Demo
|
||||
|
||||
Note that display math mode (``$ e=mc^2 $``) is not supported, but adding the
|
||||
command ``\displaystyle``, as in ``tex_demo.py``, will produce the same
|
||||
results.
|
||||
|
||||
::: tip Note
|
||||
|
||||
Certain characters require special escaping in TeX, such as:
|
||||
|
||||
``` python
|
||||
# $ % & ~ _ ^ \ { } \( \) \[ \]
|
||||
```
|
||||
|
||||
Therefore, these characters will behave differently depending on
|
||||
the rcParam ``text.usetex`` flag.
|
||||
|
||||
:::
|
||||
|
||||
## usetex with unicode
|
||||
|
||||
It is also possible to use unicode strings with the LaTeX text manager, here is
|
||||
an example taken from ``tex_demo.py``. The axis labels include Unicode text:
|
||||
|
||||
TeX Unicode Demo
|
||||
|
||||
## Postscript options
|
||||
|
||||
In order to produce encapsulated postscript files that can be embedded in a new
|
||||
LaTeX document, the default behavior of matplotlib is to distill the output,
|
||||
which removes some postscript operators used by LaTeX that are illegal in an
|
||||
eps file. This step produces results which may be unacceptable to some users,
|
||||
because the text is coarsely rasterized and converted to bitmaps, which are not
|
||||
scalable like standard postscript, and the text is not searchable. One
|
||||
workaround is to set ``ps.distiller.res`` to a higher value (perhaps 6000)
|
||||
in your rc settings, which will produce larger files but may look better and
|
||||
scale reasonably. A better workaround, which requires [Poppler](https://poppler.freedesktop.org/) or [Xpdf](http://www.xpdfreader.com/), can be
|
||||
activated by changing the ``ps.usedistiller`` rc setting to ``xpdf``. This
|
||||
alternative produces postscript without rasterizing text, so it scales
|
||||
properly, can be edited in Adobe Illustrator, and searched text in pdf
|
||||
documents.
|
||||
|
||||
## Possible hangups
|
||||
|
||||
- On Windows, the [``PATH``](https://matplotlib.orgfaq/environment_variables_faq.html#envvar-PATH) environment variable may need to be modified
|
||||
to include the directories containing the latex, dvipng and ghostscript
|
||||
executables. See [Environment Variables](https://matplotlib.orgfaq/environment_variables_faq.html#environment-variables) and
|
||||
[Setting environment variables in windows](https://matplotlib.orgfaq/environment_variables_faq.html#setting-windows-environment-variables) for details.
|
||||
- Using MiKTeX with Computer Modern fonts, if you get odd *Agg and PNG
|
||||
results, go to MiKTeX/Options and update your format files
|
||||
- On Ubuntu and Gentoo, the base texlive install does not ship with
|
||||
the type1cm package. You may need to install some of the extra
|
||||
packages to get all the goodies that come bundled with other latex
|
||||
distributions.
|
||||
- Some progress has been made so matplotlib uses the dvi files
|
||||
directly for text layout. This allows latex to be used for text
|
||||
layout with the pdf and svg backends, as well as the *Agg and PS
|
||||
backends. In the future, a latex installation may be the only
|
||||
external dependency.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Try deleting your ``.matplotlib/tex.cache`` directory. If you don't know
|
||||
where to find ``.matplotlib``, see [matplotlib configuration and cache directory locations](https://matplotlib.orgfaq/troubleshooting_faq.html#locating-matplotlib-config-dir).
|
||||
- Make sure LaTeX, dvipng and ghostscript are each working and on your
|
||||
[``PATH``](https://matplotlib.orgfaq/environment_variables_faq.html#envvar-PATH).
|
||||
- Make sure what you are trying to do is possible in a LaTeX document,
|
||||
that your LaTeX syntax is valid and that you are using raw strings
|
||||
if necessary to avoid unintended escape sequences.
|
||||
- Most problems reported on the mailing list have been cleared up by
|
||||
upgrading [Ghostscript](https://ghostscript.com/). If possible, please try upgrading to the
|
||||
latest release before reporting problems to the list.
|
||||
- The ``text.latex.preamble`` rc setting is not officially supported. This
|
||||
option provides lots of flexibility, and lots of ways to cause
|
||||
problems. Please disable this option before reporting problems to
|
||||
the mailing list.
|
||||
- If you still need help, please see [Getting help](https://matplotlib.orgfaq/troubleshooting_faq.html#reporting-problems)
|
||||
|
||||
## Download
|
||||
|
||||
- [Download Python source code: usetex.py](https://matplotlib.org/_downloads/57ba3a46dd639627a7c67fd5e227bb43/usetex.py)
|
||||
- [Download Jupyter notebook: usetex.ipynb](https://matplotlib.org/_downloads/534707238f9dbb23f6e17e815b9a3f46/usetex.ipynb)
|
||||
|
||||
Reference in New Issue
Block a user