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,497 @@
---
sidebarDepth: 3
sidebar: auto
---
# Overview of axes_grid1 toolkit
Controlling the layout of plots with the axes_grid toolkit.
## What is axes_grid1 toolkit?
*axes_grid1* is a collection of helper classes to ease displaying
(multiple) images with matplotlib. In matplotlib, the axes location
(and size) is specified in the normalized figure coordinates, which
may not be ideal for displaying images that needs to have a given
aspect ratio. For example, it helps if you have a colorbar whose
height always matches that of the image. [ImageGrid](#imagegrid), [RGB Axes](#rgb-axes) and
[AxesDivider](#axesdivider) are helper classes that deals with adjusting the
location of (multiple) Axes. They provides a framework to adjust the
position of multiple axes at the drawing time. [ParasiteAxes](#parasiteaxes)
provides twinx(or twiny)-like features so that you can plot different
data (e.g., different y-scale) in a same Axes. [AnchoredArtists](#anchoredartists)
includes custom artists which are placed at some anchored position,
like the legend.
Demo Axes Grid
## axes_grid1
### ImageGrid
A class that creates a grid of Axes. In matplotlib, the axes location
(and size) is specified in the normalized figure coordinates. This may
not be ideal for images that needs to be displayed with a given aspect
ratio. For example, displaying images of a same size with some fixed
padding between them cannot be easily done in matplotlib. ImageGrid is
used in such case.
Simple Axesgrid
- The position of each axes is determined at the drawing time (see
[AxesDivider](#axesdivider)), so that the size of the entire grid fits in the
given rectangle (like the aspect of axes). Note that in this example,
the paddings between axes are fixed even if you changes the figure
size.
- axes in the same column has a same axes width (in figure
coordinate), and similarly, axes in the same row has a same
height. The widths (height) of the axes in the same row (column) are
scaled according to their view limits (xlim or ylim).
Simple Axes Grid
- xaxis are shared among axes in a same column. Similarly, yaxis are
shared among axes in a same row. Therefore, changing axis properties
(view limits, tick location, etc. either by plot commands or using
your mouse in interactive backends) of one axes will affect all
other shared axes.
When initialized, ImageGrid creates given number (*ngrids* or *ncols* *
*nrows* if *ngrids* is None) of Axes instances. A sequence-like
interface is provided to access the individual Axes instances (e.g.,
grid[0] is the first Axes in the grid. See below for the order of
axes).
ImageGrid takes following arguments,
---
Name
Default
Description
fig
 
 
rect
 
 
nrows_ncols
 
number of rows and cols. e.g., (2,2)
ngrids
None
number of grids. nrows x ncols if None
direction
"row"
increasing direction of axes number. [row|column]
axes_pad
0.02
pad between axes in inches
add_all
True
Add axes to figures if True
share_all
False
xaxis & yaxis of all axes are shared if True
aspect
True
aspect of axes
label_mode
"L"
location of tick labels thaw will be displayed.
"1" (only the lower left axes),
"L" (left most and bottom most axes),
or "all".
cbar_mode
None
[None|single|each]
cbar_location
"right"
[right|top]
cbar_pad
None
pad between image axes and colorbar axes
cbar_size
"5%"
size of the colorbar
axes_class
None
 
*rect*
*direction*
*aspect*
*share_all*
*direction*
direction of increasing axes number. For "row",
---
grid[0]
grid[1]
grid[2]
grid[3]
For "column",
---
grid[0]
grid[2]
grid[1]
grid[3]
You can also create a colorbar (or colorbars). You can have colorbar
for each axes (cbar_mode="each"), or you can have a single colorbar
for the grid (cbar_mode="single"). The colorbar can be placed on your
right, or top. The axes for each colorbar is stored as a *cbar_axes*
attribute.
The examples below show what you can do with ImageGrid.
Demo Axes Grid
### AxesDivider Class
Behind the scene, the ImageGrid class and the RGBAxes class utilize the
AxesDivider class, whose role is to calculate the location of the axes
at drawing time. While a more about the AxesDivider is (will be)
explained in (yet to be written) AxesDividerGuide, direct use of the
AxesDivider class will not be necessary for most users. The
axes_divider module provides a helper function make_axes_locatable,
which can be useful. It takes a existing axes instance and create a
divider for it.
``` python
ax = subplot(1,1,1)
divider = make_axes_locatable(ax)
```
*make_axes_locatable* returns an instance of the AxesLocator class,
derived from the Locator. It provides *append_axes* method that
creates a new axes on the given side of ("top", "right", "bottom" and
"left") of the original axes.
### colorbar whose height (or width) in sync with the master axes
Simple Colorbar
#### scatter_hist.py with AxesDivider
The "scatter_hist.py" example in mpl can be rewritten using
*make_axes_locatable*.
``` python
axScatter = subplot(111)
axScatter.scatter(x, y)
axScatter.set_aspect(1.)
# create new axes on the right and on the top of the current axes.
divider = make_axes_locatable(axScatter)
axHistx = divider.append_axes("top", size=1.2, pad=0.1, sharex=axScatter)
axHisty = divider.append_axes("right", size=1.2, pad=0.1, sharey=axScatter)
# the scatter plot:
# histograms
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')
```
See the full source code below.
Scatter Hist
The scatter_hist using the AxesDivider has some advantage over the
original scatter_hist.py in mpl. For example, you can set the aspect
ratio of the scatter plot, even with the x-axis or y-axis is shared
accordingly.
### ParasiteAxes
The ParasiteAxes is an axes whose location is identical to its host
axes. The location is adjusted in the drawing time, thus it works even
if the host change its location (e.g., images).
In most cases, you first create a host axes, which provides a few
method that can be used to create parasite axes. They are *twinx*,
*twiny* (which are similar to twinx and twiny in the matplotlib) and
*twin*. *twin* takes an arbitrary transformation that maps between the
data coordinates of the host axes and the parasite axes. *draw*
method of the parasite axes are never called. Instead, host axes
collects artists in parasite axes and draw them as if they belong to
the host axes, i.e., artists in parasite axes are merged to those of
the host axes and then drawn according to their zorder. The host and
parasite axes modifies some of the axes behavior. For example, color
cycle for plot lines are shared between host and parasites. Also, the
legend command in host, creates a legend that includes lines in the
parasite axes. To create a host axes, you may use *host_subplot* or
*host_axes* command.
#### Example 1. twinx
Parasite Simple
#### Example 2. twin
*twin* without a transform argument assumes that the parasite axes has the
same data transform as the host. This can be useful when you want the
top(or right)-axis to have different tick-locations, tick-labels, or
tick-formatter for bottom(or left)-axis.
``` python
ax2 = ax.twin() # now, ax2 is responsible for "top" axis and "right" axis
ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi])
ax2.set_xticklabels(["0", r"$\frac{1}{2}\pi$",
r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])
```
Simple Axisline4
A more sophisticated example using twin. Note that if you change the
x-limit in the host axes, the x-limit of the parasite axes will change
accordingly.
Parasite Simple2
### AnchoredArtists
It's a collection of artists whose location is anchored to the (axes)
bbox, like the legend. It is derived from *OffsetBox* in mpl, and
artist need to be drawn in the canvas coordinate. But, there is a
limited support for an arbitrary transform. For example, the ellipse
in the example below will have width and height in the data
coordinate.
Simple Anchored Artists
### InsetLocator
[``mpl_toolkits.axes_grid1.inset_locator``](https://matplotlib.orgapi/_as_gen/mpl_toolkits.axes_grid1.inset_locator.html#module-mpl_toolkits.axes_grid1.inset_locator) provides helper classes
and functions to place your (inset) axes at the anchored position of
the parent axes, similarly to AnchoredArtist.
Using [``mpl_toolkits.axes_grid1.inset_locator.inset_axes()``](https://matplotlib.orgapi/_as_gen/mpl_toolkits.axes_grid1.inset_locator.inset_axes.html#mpl_toolkits.axes_grid1.inset_locator.inset_axes), you
can have inset axes whose size is either fixed, or a fixed proportion
of the parent axes. For example,:
``` python
inset_axes = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
loc='lower left')
```
creates an inset axes whose width is 30% of the parent axes and whose
height is fixed at 1 inch.
You may creates your inset whose size is determined so that the data
scale of the inset axes to be that of the parent axes multiplied by
some factor. For example,
``` python
inset_axes = zoomed_inset_axes(ax,
0.5, # zoom = 0.5
loc='upper right')
```
creates an inset axes whose data scale is half of the parent axes.
Here is complete examples.
Inset Locator Demo
For example, ``zoomed_inset_axes()`` can be used when you want the
inset represents the zoom-up of the small portion in the parent axes.
And ``mpl_toolkits/axes_grid/inset_locator`` provides a helper
function ``mark_inset()`` to mark the location of the area
represented by the inset axes.
Inset Locator Demo2
#### RGB Axes
RGBAxes is a helper class to conveniently show RGB composite
images. Like ImageGrid, the location of axes are adjusted so that the
area occupied by them fits in a given rectangle. Also, the xaxis and
yaxis of each axes are shared.
``` python
from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes
fig = plt.figure()
ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8])
r, g, b = get_rgb() # r,g,b are 2-d images
ax.imshow_rgb(r, g, b,
origin="lower", interpolation="nearest")
```
Simple Rgb
## AxesDivider
The axes_divider module provides helper classes to adjust the axes
positions of a set of images at drawing time.
- [``axes_size``](https://matplotlib.orgapi/_as_gen/mpl_toolkits.axes_grid1.axes_size.html#module-mpl_toolkits.axes_grid1.axes_size) provides a class of
units that are used to determine the size of each axes. For example,
you can specify a fixed size.
- ``Divider`` is the class
that calculates the axes position. It divides the given
rectangular area into several areas. The divider is initialized by
setting the lists of horizontal and vertical sizes on which the division
will be based. Then use
``new_locator()``,
which returns a callable object that can be used to set the
axes_locator of the axes.
First, initialize the divider by specifying its grids, i.e.,
horizontal and vertical.
for example,:
``` python
rect = [0.2, 0.2, 0.6, 0.6]
horiz=[h0, h1, h2, h3]
vert=[v0, v1, v2]
divider = Divider(fig, rect, horiz, vert)
```
where, rect is a bounds of the box that will be divided and h0,..h3,
v0,..v2 need to be an instance of classes in the
[``axes_size``](https://matplotlib.orgapi/_as_gen/mpl_toolkits.axes_grid1.axes_size.html#module-mpl_toolkits.axes_grid1.axes_size). They have *get_size* method
that returns a tuple of two floats. The first float is the relative
size, and the second float is the absolute size. Consider a following
grid.
---
v0
 
 
 
v1
 
 
 
h0,v2
h1
h2
h3
- v0 => 0, 2
- v1 => 2, 0
- v2 => 3, 0
The height of the bottom row is always 2 (axes_divider internally
assumes that the unit is inches). The first and the second rows have a
height ratio of 2:3. For example, if the total height of the grid is 6,
then the first and second row will each occupy 2/(2+3) and 3/(2+3) of
(6-1) inches. The widths of the horizontal columns will be similarly
determined. When the aspect ratio is set, the total height (or width) will
be adjusted accordingly.
The [``mpl_toolkits.axes_grid1.axes_size``](https://matplotlib.orgapi/_as_gen/mpl_toolkits.axes_grid1.axes_size.html#module-mpl_toolkits.axes_grid1.axes_size) contains several classes
that can be used to set the horizontal and vertical configurations. For
example, for vertical configuration one could use:
``` python
from mpl_toolkits.axes_grid1.axes_size import Fixed, Scaled
vert = [Fixed(2), Scaled(2), Scaled(3)]
```
After you set up the divider object, then you create a locator
instance that will be given to the axes object.:
``` python
locator = divider.new_locator(nx=0, ny=1)
ax.set_axes_locator(locator)
```
The return value of the new_locator method is an instance of the
AxesLocator class. It is a callable object that returns the
location and size of the cell at the first column and the second row.
You may create a locator that spans over multiple cells.:
``` python
locator = divider.new_locator(nx=0, nx=2, ny=1)
```
The above locator, when called, will return the position and size of
the cells spanning the first and second column and the first row. In
this example, it will return [0:2, 1].
See the example,
Simple Axes Divider2
You can adjust the size of each axes according to its x or y
data limits (AxesX and AxesY).
Simple Axes Divider3
## Download
- [Download Python source code: axes_grid.py](https://matplotlib.org/_downloads/cc46224ebb7a7afda7d8b6f3a1e58c06/axes_grid.py)
- [Download Jupyter notebook: axes_grid.ipynb](https://matplotlib.org/_downloads/c0b6a1c863337a7a54913ff3820e598b/axes_grid.ipynb)

View File

@@ -0,0 +1,617 @@
---
sidebarDepth: 3
sidebar: auto
---
# Overview of axisartist toolkit
The axisartist toolkit tutorial.
::: danger Warning
*axisartist* uses a custom Axes class
(derived from the mpl's original Axes class).
As a side effect, some commands (mostly tick-related) do not work.
:::
The *axisartist* contains a custom Axes class that is meant to support
curvilinear grids (e.g., the world coordinate system in astronomy).
Unlike mpl's original Axes class which uses Axes.xaxis and Axes.yaxis
to draw ticks, ticklines, etc., axisartist uses a special
artist (AxisArtist) that can handle ticks, ticklines, etc. for
curved coordinate systems.
Demo Floating Axis
Since it uses special artists, some Matplotlib commands that work on
Axes.xaxis and Axes.yaxis may not work.
## axisartist
The *axisartist* module provides a custom (and very experimental) Axes
class, where each axis (left, right, top, and bottom) have a separate
associated artist which is responsible for drawing the axis-line, ticks,
ticklabels, and labels. You can also create your own axis, which can pass
through a fixed position in the axes coordinate, or a fixed position
in the data coordinate (i.e., the axis floats around when viewlimit
changes).
The axes class, by default, has its xaxis and yaxis invisible, and
has 4 additional artists which are responsible for drawing the 4 axis spines in
"left", "right", "bottom", and "top". They are accessed as
ax.axis["left"], ax.axis["right"], and so on, i.e., ax.axis is a
dictionary that contains artists (note that ax.axis is still a
callable method and it behaves as an original Axes.axis method in
Matplotlib).
To create an axes,
``` python
import mpl_toolkits.axisartist as AA
fig = plt.figure()
ax = AA.Axes(fig, [0.1, 0.1, 0.8, 0.8])
fig.add_axes(ax)
```
or to create a subplot
``` python
ax = AA.Subplot(fig, 111)
fig.add_subplot(ax)
```
For example, you can hide the right and top spines using:
``` python
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
```
Simple Axisline3
It is also possible to add a horizontal axis. For example, you may have an
horizontal axis at y=0 (in data coordinate).
``` python
ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0, value=0)
```
Simple Axisartist1
Or a fixed axis with some offset
``` python
# make new (right-side) yaxis, but with some offset
ax.axis["right2"] = ax.new_fixed_axis(loc="right",
offset=(20, 0))
```
### axisartist with ParasiteAxes
Most commands in the axes_grid1 toolkit can take an axes_class keyword
argument, and the commands create an axes of the given class. For example,
to create a host subplot with axisartist.Axes,
``` python
import mpl_toolkits.axisartist as AA
from mpl_toolkits.axes_grid1 import host_subplot
host = host_subplot(111, axes_class=AA.Axes)
```
Here is an example that uses ParasiteAxes.
Demo Parasite Axes2
### Curvilinear Grid
The motivation behind the AxisArtist module is to support a curvilinear grid
and ticks.
Demo Curvelinear Grid
### Floating Axes
AxisArtist also supports a Floating Axes whose outer axes are defined as
floating axis.
Demo Floating Axes
## axisartist namespace
The *axisartist* namespace includes a derived Axes implementation. The
biggest difference is that the artists responsible to draw axis line,
ticks, ticklabel and axis labels are separated out from the mpl's Axis
class, which are much more than artists in the original mpl. This
change was strongly motivated to support curvilinear grid. Here are a
few things that mpl_toolkits.axisartist.Axes is different from original
Axes from mpl.
- Axis elements (axis line(spine), ticks, ticklabel and axis labels)
are drawn by a AxisArtist instance. Unlike Axis, left, right, top
and bottom axis are drawn by separate artists. And each of them may
have different tick location and different tick labels.
- gridlines are drawn by a Gridlines instance. The change was
motivated that in curvilinear coordinate, a gridline may not cross
axis-lines (i.e., no associated ticks). In the original Axes class,
gridlines are tied to ticks.
- ticklines can be rotated if necessary (i.e, along the gridlines)
In summary, all these changes was to support
- a curvilinear grid.
- a floating axis
Demo Floating Axis
*mpl_toolkits.axisartist.Axes* class defines a *axis* attribute, which
is a dictionary of AxisArtist instances. By default, the dictionary
has 4 AxisArtist instances, responsible for drawing of left, right,
bottom and top axis.
xaxis and yaxis attributes are still available, however they are set
to not visible. As separate artists are used for rendering axis, some
axis-related method in mpl may have no effect.
In addition to AxisArtist instances, the mpl_toolkits.axisartist.Axes will
have *gridlines* attribute (Gridlines), which obviously draws grid
lines.
In both AxisArtist and Gridlines, the calculation of tick and grid
location is delegated to an instance of GridHelper class.
mpl_toolkits.axisartist.Axes class uses GridHelperRectlinear as a grid
helper. The GridHelperRectlinear class is a wrapper around the *xaxis*
and *yaxis* of mpl's original Axes, and it was meant to work as the
way how mpl's original axes works. For example, tick location changes
using set_ticks method and etc. should work as expected. But change in
artist properties (e.g., color) will not work in general, although
some effort has been made so that some often-change attributes (color,
etc.) are respected.
## AxisArtist
AxisArtist can be considered as a container artist with following
attributes which will draw ticks, labels, etc.
- line
- major_ticks, major_ticklabels
- minor_ticks, minor_ticklabels
- offsetText
- label
### line
Derived from Line2d class. Responsible for drawing a spinal(?) line.
### major_ticks, minor_ticks
Derived from Line2d class. Note that ticks are markers.
### major_ticklabels, minor_ticklabels
Derived from Text. Note that it is not a list of Text artist, but a
single artist (similar to a collection).
### axislabel
Derived from Text.
## Default AxisArtists
By default, following for axis artists are defined.:
``` python
ax.axis["left"], ax.axis["bottom"], ax.axis["right"], ax.axis["top"]
```
The ticklabels and axislabel of the top and the right axis are set to
not visible.
For example, if you want to change the color attributes of
major_ticklabels of the bottom x-axis
``` python
ax.axis["bottom"].major_ticklabels.set_color("b")
```
Similarly, to make ticklabels invisible
``` python
ax.axis["bottom"].major_ticklabels.set_visible(False)
```
AxisArtist provides a helper method to control the visibility of ticks,
ticklabels, and label. To make ticklabel invisible,
``` python
ax.axis["bottom"].toggle(ticklabels=False)
```
To make all of ticks, ticklabels, and (axis) label invisible
``` python
ax.axis["bottom"].toggle(all=False)
```
To turn all off but ticks on
``` python
ax.axis["bottom"].toggle(all=False, ticks=True)
```
To turn all on but (axis) label off
``` python
ax.axis["bottom"].toggle(all=True, label=False))
```
ax.axis's __getitem__ method can take multiple axis names. For
example, to turn ticklabels of "top" and "right" axis on,
``` python
ax.axis["top","right"].toggle(ticklabels=True))
```
Note that 'ax.axis["top","right"]' returns a simple proxy object that translate above code to something like below.
``` python
for n in ["top","right"]:
ax.axis[n].toggle(ticklabels=True))
```
So, any return values in the for loop are ignored. And you should not
use it anything more than a simple method.
Like the list indexing ":" means all items, i.e.,
``` python
ax.axis[:].major_ticks.set_color("r")
```
changes tick color in all axis.
## HowTo
1. Changing tick locations and label.
Same as the original mpl's axes.:
``` python
ax.set_xticks([1,2,3])
```
1. Changing axis properties like color, etc.
Change the properties of appropriate artists. For example, to change
the color of the ticklabels:
``` python
ax.axis["left"].major_ticklabels.set_color("r")
```
## Rotation and Alignment of TickLabels
This is also quite different from the original mpl and can be
confusing. When you want to rotate the ticklabels, first consider
using "set_axis_direction" method.
``` python
ax1.axis["left"].major_ticklabels.set_axis_direction("top")
ax1.axis["right"].label.set_axis_direction("left")
```
Simple Axis Direction01
The parameter for set_axis_direction is one of ["left", "right",
"bottom", "top"].
You must understand some underlying concept of directions.
On the other hand, there is a concept of "axis_direction". This is a
default setting of above properties for each, "bottom", "left", "top",
and "right" axis.
---
?
?
left
bottom
right
top
axislabel
direction
'-'
'+'
'+'
'-'
axislabel
rotation
180
0
0
180
axislabel
va
center
top
center
bottom
axislabel
ha
right
center
right
center
ticklabel
direction
'-'
'+'
'+'
'-'
ticklabels
rotation
90
0
-90
180
ticklabel
ha
right
center
right
center
ticklabel
va
center
baseline
center
baseline
And, 'set_axis_direction("top")' means to adjust the text rotation
etc, for settings suitable for "top" axis. The concept of axis
direction can be more clear with curved axis.
Demo Axis Direction
The axis_direction can be adjusted in the AxisArtist level, or in the
level of its child artists, i.e., ticks, ticklabels, and axis-label.
``` python
ax1.axis["left"].set_axis_direction("top")
```
changes axis_direction of all the associated artist with the "left"
axis, while
``` python
ax1.axis["left"].major_ticklabels.set_axis_direction("top")
```
changes the axis_direction of only the major_ticklabels. Note that
set_axis_direction in the AxisArtist level changes the
ticklabel_direction and label_direction, while changing the
axis_direction of ticks, ticklabels, and axis-label does not affect
them.
If you want to make ticks outward and ticklabels inside the axes,
use invert_ticklabel_direction method.
``` python
ax.axis[:].invert_ticklabel_direction()
```
A related method is "set_tick_out". It makes ticks outward (as a
matter of fact, it makes ticks toward the opposite direction of the
default direction).
``` python
ax.axis[:].major_ticks.set_tick_out(True)
```
Simple Axis Direction03
So, in summary,
- AxisArtist's methods
set_axis_direction : "left", "right", "bottom", or "top"
set_ticklabel_direction : "+" or "-"
set_axislabel_direction : "+" or "-"
invert_ticklabel_direction
- set_axis_direction : "left", "right", "bottom", or "top"
- set_ticklabel_direction : "+" or "-"
- set_axislabel_direction : "+" or "-"
- invert_ticklabel_direction
- Ticks' methods (major_ticks and minor_ticks)
set_tick_out : True or False
set_ticksize : size in points
- set_tick_out : True or False
- set_ticksize : size in points
- TickLabels' methods (major_ticklabels and minor_ticklabels)
set_axis_direction : "left", "right", "bottom", or "top"
set_rotation : angle with respect to the reference direction
set_ha and set_va : see below
- set_axis_direction : "left", "right", "bottom", or "top"
- set_rotation : angle with respect to the reference direction
- set_ha and set_va : see below
- AxisLabels' methods (label)
set_axis_direction : "left", "right", "bottom", or "top"
set_rotation : angle with respect to the reference direction
set_ha and set_va
- set_axis_direction : "left", "right", "bottom", or "top"
- set_rotation : angle with respect to the reference direction
- set_ha and set_va
### Adjusting ticklabels alignment
Alignment of TickLabels are treated specially. See below
Demo Ticklabel Alignment
### Adjusting pad
To change the pad between ticks and ticklabels
``` python
ax.axis["left"].major_ticklabels.set_pad(10)
```
Or ticklabels and axis-label
``` python
ax.axis["left"].label.set_pad(10)
```
Simple Axis Pad
## GridHelper
To actually define a curvilinear coordinate, you have to use your own
grid helper. A generalised version of grid helper class is supplied
and this class should suffice in most of cases. A user may provide
two functions which defines a transformation (and its inverse pair)
from the curved coordinate to (rectilinear) image coordinate. Note that
while ticks and grids are drawn for curved coordinate, the data
transform of the axes itself (ax.transData) is still rectilinear
(image) coordinate.
``` python
from mpl_toolkits.axisartist.grid_helper_curvelinear \
import GridHelperCurveLinear
from mpl_toolkits.axisartist import Subplot
# from curved coordinate to rectlinear coordinate.
def tr(x, y):
x, y = np.asarray(x), np.asarray(y)
return x, y-x
# from rectlinear coordinate to curved coordinate.
def inv_tr(x,y):
x, y = np.asarray(x), np.asarray(y)
return x, y+x
grid_helper = GridHelperCurveLinear((tr, inv_tr))
ax1 = Subplot(fig, 1, 1, 1, grid_helper=grid_helper)
fig.add_subplot(ax1)
```
You may use matplotlib's Transform instance instead (but a
inverse transformation must be defined). Often, coordinate range in a
curved coordinate system may have a limited range, or may have
cycles. In those cases, a more customized version of grid helper is
required.
``` python
import mpl_toolkits.axisartist.angle_helper as angle_helper
# PolarAxes.PolarTransform takes radian. However, we want our coordinate
# system in degree
tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
# extreme finder : find a range of coordinate.
# 20, 20 : number of sampling points along x, y direction
# The first coordinate (longitude, but theta in polar)
# has a cycle of 360 degree.
# The second coordinate (latitude, but radius in polar) has a minimum of 0
extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
lon_cycle = 360,
lat_cycle = None,
lon_minmax = None,
lat_minmax = (0, np.inf),
)
# Find a grid values appropriate for the coordinate (degree,
# minute, second). The argument is a approximate number of grids.
grid_locator1 = angle_helper.LocatorDMS(12)
# And also uses an appropriate formatter. Note that,the
# acceptable Locator and Formatter class is a bit different than
# that of mpl's, and you cannot directly use mpl's Locator and
# Formatter here (but may be possible in the future).
tick_formatter1 = angle_helper.FormatterDMS()
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
tick_formatter1=tick_formatter1
)
```
Again, the *transData* of the axes is still a rectilinear coordinate
(image coordinate). You may manually do conversion between two
coordinates, or you may use Parasite Axes for convenience.:
``` python
ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)
# A parasite axes with given transform
ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
# note that ax2.transData == tr + ax1.transData
# Anything you draw in ax2 will match the ticks and grids of ax1.
ax1.parasites.append(ax2)
```
Demo Curvelinear Grid
## FloatingAxis
A floating axis is an axis one of whose data coordinate is fixed, i.e,
its location is not fixed in Axes coordinate but changes as axes data
limits changes. A floating axis can be created using
*new_floating_axis* method. However, it is your responsibility that
the resulting AxisArtist is properly added to the axes. A recommended
way is to add it as an item of Axes's axis attribute.:
``` python
# floating axis whose first (index starts from 0) coordinate
# (theta) is fixed at 60
ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)
axis.label.set_text(r"$\theta = 60^{\circ}$")
axis.label.set_visible(True)
```
See the first example of this page.
## Current Limitations and TODO's
The code need more refinement. Here is a incomplete list of issues and TODO's
- No easy way to support a user customized tick location (for
curvilinear grid). A new Locator class needs to be created.
- FloatingAxis may have coordinate limits, e.g., a floating axis of x
= 0, but y only spans from 0 to 1.
- The location of axislabel of FloatingAxis needs to be optionally
given as a coordinate value. ex, a floating axis of x=0 with label at y=1
## Download
- [Download Python source code: axisartist.py](https://matplotlib.org/_downloads/009aa8b612fe75c3b3046dbffcd0d1c7/axisartist.py)
- [Download Jupyter notebook: axisartist.ipynb](https://matplotlib.org/_downloads/47bc25cb4e9c18eccf1385f78c4ea405/axisartist.ipynb)

View File

@@ -0,0 +1,652 @@
---
sidebarDepth: 3
sidebar: auto
---
# The mplot3d Toolkit
Generating 3D plots using the mplot3d toolkit.
Contents
- [The mplot3d Toolkit](#the-mplot3d-toolkit)
[Getting started](#getting-started)
[Line plots](#line-plots)
[Scatter plots](#scatter-plots)
[Wireframe plots](#wireframe-plots)
[Surface plots](#surface-plots)
[Tri-Surface plots](#tri-surface-plots)
[Contour plots](#contour-plots)
[Filled contour plots](#filled-contour-plots)
[Polygon plots](#polygon-plots)
[Bar plots](#bar-plots)
[Quiver](#quiver)
[2D plots in 3D](#d-plots-in-3d)
[Text](#text)
[Subplotting](#subplotting)
- [Getting started](#getting-started)
[Line plots](#line-plots)
[Scatter plots](#scatter-plots)
[Wireframe plots](#wireframe-plots)
[Surface plots](#surface-plots)
[Tri-Surface plots](#tri-surface-plots)
[Contour plots](#contour-plots)
[Filled contour plots](#filled-contour-plots)
[Polygon plots](#polygon-plots)
[Bar plots](#bar-plots)
[Quiver](#quiver)
[2D plots in 3D](#d-plots-in-3d)
[Text](#text)
[Subplotting](#subplotting)
- [Line plots](#line-plots)
- [Scatter plots](#scatter-plots)
- [Wireframe plots](#wireframe-plots)
- [Surface plots](#surface-plots)
- [Tri-Surface plots](#tri-surface-plots)
- [Contour plots](#contour-plots)
- [Filled contour plots](#filled-contour-plots)
- [Polygon plots](#polygon-plots)
- [Bar plots](#bar-plots)
- [Quiver](#quiver)
- [2D plots in 3D](#d-plots-in-3d)
- [Text](#text)
- [Subplotting](#subplotting)
## Getting started
An Axes3D object is created just like any other axes using
the projection='3d' keyword.
Create a new [``matplotlib.figure.Figure``](https://matplotlib.orgapi/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure) and
add a new axes to it of type ``Axes3D``:
``` python
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
```
*New in version 1.0.0:* This approach is the preferred method of creating a 3D axes.
::: tip Note
Prior to version 1.0.0, the method of creating a 3D axes was
different. For those using older versions of matplotlib, change
``ax = fig.add_subplot(111, projection='3d')``
to ``ax = Axes3D(fig)``.
:::
See the [mplot3d FAQ](https://matplotlib.orgapi/toolkits/mplot3d/faq.html#toolkit-mplot3d-faq) for more information about the mplot3d
toolkit.
### Line plots
``Axes3D.````plot``(*self*, *xs*, *ys*, **args*, *zdir='z'*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.plot)[¶](#mpl_toolkits.mplot3d.Axes3D.plot)
Plot 2D or 3D data.
---
Parameters:
xs : 1D array-like
x coordinates of vertices.
ys : 1D array-like
y coordinates of vertices.
zs : scalar or 1D array-like
z coordinates of vertices; either one for all points or one for
each point.
zdir : {'x', 'y', 'z'}
When plotting 2D data, the direction to use as z ('x', 'y' or 'z');
defaults to 'z'.
**kwargs
Other arguments are forwarded to [matplotlib.axes.Axes.plot](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot).
Lines3d
### Scatter plots
``Axes3D.````scatter``(*self*, *xs*, *ys*, *zs=0*, *zdir='z'*, *s=20*, *c=None*, *depthshade=True*, **args*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.scatter)[¶](#mpl_toolkits.mplot3d.Axes3D.scatter)
Create a scatter plot.
---
Parameters:
xs, ys : array-like
The data positions.
zs : float or array-like, optional, default: 0
The z-positions. Either an array of the same length as xs and
ys or a single value to place all points in the same plane.
zdir : {'x', 'y', 'z', '-x', '-y', '-z'}, optional, default: 'z'
The axis direction for the zs. This is useful when plotting 2D
data on a 3D Axes. The data must be passed as xs, ys. Setting
zdir to 'y' then plots the data to the x-z-plane.
See also [Plot 2D data on 3D plot](https://matplotlib.org/../gallery/mplot3d/2dcollections3d.html).
s : scalar or array-like, optional, default: 20
The marker size in points**2. Either an array of the same length
as xs and ys or a single value to make all markers the same
size.
c : color, sequence, or sequence of color, optional
The marker color. Possible values:
A single color format string.
A sequence of color specifications of length n.
A sequence of n numbers to be mapped to colors using cmap and
norm.
A 2-D array in which the rows are RGB or RGBA.
For more details see the c argument of [[scatter](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.scatter.html#matplotlib.axes.Axes.scatter)](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.scatter.html#matplotlib.axes.Axes.scatter).
depthshade : bool, optional, default: True
Whether to shade the scatter markers to give the appearance of
depth.
**kwargs
All other arguments are passed on to scatter.
Returns:
paths : [PathCollection](https://matplotlib.org/../api/collections_api.html#matplotlib.collections.PathCollection)
Scatter3d
### Wireframe plots
``Axes3D.````plot_wireframe``(*self*, *X*, *Y*, *Z*, **args*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.plot_wireframe)[¶](#mpl_toolkits.mplot3d.Axes3D.plot_wireframe)
Plot a 3D wireframe.
::: tip Note
The *rcount* and *ccount* kwargs, which both default to 50,
determine the maximum number of samples used in each direction. If
the input data is larger, it will be downsampled (by slicing) to
these numbers of points.
:::
---
Parameters:
X, Y, Z : 2d arrays
Data values.
rcount, ccount : int
Maximum number of samples used in each direction. If the input
data is larger, it will be downsampled (by slicing) to these
numbers of points. Setting a count to zero causes the data to be
not sampled in the corresponding direction, producing a 3D line
plot rather than a wireframe plot. Defaults to 50.
New in version 2.0.
rstride, cstride : int
Downsampling stride in each direction. These arguments are
mutually exclusive with rcount and ccount. If only one of
rstride or cstride is set, the other defaults to 1. Setting a
stride to zero causes the data to be not sampled in the
corresponding direction, producing a 3D line plot rather than a
wireframe plot.
'classic' mode uses a default of rstride = cstride = 1 instead
of the new default of rcount = ccount = 50.
**kwargs
Other arguments are forwarded to [Line3DCollection](https://matplotlib.org/../api/_as_gen/mpl_toolkits.mplot3d.art3d.Line3DCollection.html#mpl_toolkits.mplot3d.art3d.Line3DCollection).
Wire3d
### Surface plots
``Axes3D.````plot_surface``(*self*, *X*, *Y*, *Z*, **args*, *norm=None*, *vmin=None*, *vmax=None*, *lightsource=None*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.plot_surface)[¶](#mpl_toolkits.mplot3d.Axes3D.plot_surface)
Create a surface plot.
By default it will be colored in shades of a solid color, but it also
supports color mapping by supplying the *cmap* argument.
::: tip Note
The *rcount* and *ccount* kwargs, which both default to 50,
determine the maximum number of samples used in each direction. If
the input data is larger, it will be downsampled (by slicing) to
these numbers of points.
:::
---
Parameters:
X, Y, Z : 2d arrays
Data values.
rcount, ccount : int
Maximum number of samples used in each direction. If the input
data is larger, it will be downsampled (by slicing) to these
numbers of points. Defaults to 50.
New in version 2.0.
rstride, cstride : int
Downsampling stride in each direction. These arguments are
mutually exclusive with rcount and ccount. If only one of
rstride or cstride is set, the other defaults to 10.
'classic' mode uses a default of rstride = cstride = 10 instead
of the new default of rcount = ccount = 50.
color : color-like
Color of the surface patches.
cmap : Colormap
Colormap of the surface patches.
facecolors : array-like of colors.
Colors of each individual patch.
norm : Normalize
Normalization for the colormap.
vmin, vmax : float
Bounds for the normalization.
shade : bool
Whether to shade the facecolors. Defaults to True. Shading is
always disabled when cmap is specified.
lightsource : [LightSource](https://matplotlib.org/../api/_as_gen/matplotlib.colors.LightSource.html#matplotlib.colors.LightSource)
The lightsource to use when shade is True.
**kwargs
Other arguments are forwarded to [Poly3DCollection](https://matplotlib.org/../api/_as_gen/mpl_toolkits.mplot3d.art3d.Poly3DCollection.html#mpl_toolkits.mplot3d.art3d.Poly3DCollection).
Surface3d
Surface3d 2
Surface3d 3
### Tri-Surface plots
``Axes3D.````plot_trisurf``(*self*, **args*, *color=None*, *norm=None*, *vmin=None*, *vmax=None*, *lightsource=None*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.plot_trisurf)[¶](#mpl_toolkits.mplot3d.Axes3D.plot_trisurf)
Plot a triangulated surface.
The (optional) triangulation can be specified in one of two ways;
either:
``` python
plot_trisurf(triangulation, ...)
```
where triangulation is a [``Triangulation``](https://matplotlib.orgapi/tri_api.html#matplotlib.tri.Triangulation)
object, or:
``` python
plot_trisurf(X, Y, ...)
plot_trisurf(X, Y, triangles, ...)
plot_trisurf(X, Y, triangles=triangles, ...)
```
in which case a Triangulation object will be created. See
[``Triangulation``](https://matplotlib.orgapi/tri_api.html#matplotlib.tri.Triangulation) for a explanation of
these possibilities.
The remaining arguments are:
``` python
plot_trisurf(..., Z)
```
where *Z* is the array of values to contour, one per point
in the triangulation.
---
Parameters:
X, Y, Z : array-like
Data values as 1D arrays.
color
Color of the surface patches.
cmap
A colormap for the surface patches.
norm : Normalize
An instance of Normalize to map values to colors.
vmin, vmax : scalar, optional, default: None
Minimum and maximum value to map.
shade : bool
Whether to shade the facecolors. Defaults to True. Shading is
always disabled when cmap is specified.
lightsource : [LightSource](https://matplotlib.org/../api/_as_gen/matplotlib.colors.LightSource.html#matplotlib.colors.LightSource)
The lightsource to use when shade is True.
**kwargs
All other arguments are passed on to
[Poly3DCollection](https://matplotlib.org/../api/_as_gen/mpl_toolkits.mplot3d.art3d.Poly3DCollection.html#mpl_toolkits.mplot3d.art3d.Poly3DCollection)
Examples
([Source code](https://matplotlib.orggallery/mplot3d/trisurf3d.py), [png](https://matplotlib.orggallery/mplot3d/trisurf3d.png), [pdf](https://matplotlib.orggallery/mplot3d/trisurf3d.pdf))
![trisurf3d1](https://matplotlib.org/_images/trisurf3d1.png)
([Source code](https://matplotlib.orggallery/mplot3d/trisurf3d_2.py), [png](https://matplotlib.orggallery/mplot3d/trisurf3d_2.png), [pdf](https://matplotlib.orggallery/mplot3d/trisurf3d_2.pdf))
![trisurf3d_21](https://matplotlib.org/_images/trisurf3d_21.png)
*New in version 1.2.0:* This plotting function was added for the v1.2.0 release.
Trisurf3d
### Contour plots
``Axes3D.````contour``(*self*, *X*, *Y*, *Z*, **args*, *extend3d=False*, *stride=5*, *zdir='z'*, *offset=None*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.contour)[¶](#mpl_toolkits.mplot3d.Axes3D.contour)
Create a 3D contour plot.
---
Parameters:
X, Y, Z : array-likes
Input data.
extend3d : bool
Whether to extend contour in 3D; defaults to False.
stride : int
Step size for extending contour.
zdir : {'x', 'y', 'z'}
The direction to use; defaults to 'z'.
offset : scalar
If specified, plot a projection of the contour lines at this
position in a plane normal to zdir
*args, **kwargs
Other arguments are forwarded to [matplotlib.axes.Axes.contour](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.contour.html#matplotlib.axes.Axes.contour).
Returns:
matplotlib.contour.QuadContourSet
Contour3d
Contour3d 2
Contour3d 3
### Filled contour plots
``Axes3D.````contourf``(*self*, *X*, *Y*, *Z*, **args*, *zdir='z'*, *offset=None*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.contourf)[¶](#mpl_toolkits.mplot3d.Axes3D.contourf)
Create a 3D filled contour plot.
---
Parameters:
X, Y, Z : array-likes
Input data.
zdir : {'x', 'y', 'z'}
The direction to use; defaults to 'z'.
offset : scalar
If specified, plot a projection of the contour lines at this
position in a plane normal to zdir
*args, **kwargs
Other arguments are forwarded to [matplotlib.axes.Axes.contourf](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.contourf.html#matplotlib.axes.Axes.contourf).
Returns:
matplotlib.contour.QuadContourSet
Notes
*New in version 1.1.0:* The *zdir* and *offset* parameters.
Contourf3d
*New in version 1.1.0:* The feature demoed in the second contourf3d example was enabled as a
result of a bugfix for version 1.1.0.
### Polygon plots
``Axes3D.````add_collection3d``(*self*, *col*, *zs=0*, *zdir='z'*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.add_collection3d)[¶](#mpl_toolkits.mplot3d.Axes3D.add_collection3d)
Add a 3D collection object to the plot.
2D collection types are converted to a 3D version by
modifying the object and adding z coordinate information.
Supported are:
- PolyCollection
- LineCollection
- PatchCollection
Polys3d
### Bar plots
``Axes3D.````bar``(*self*, *left*, *height*, *zs=0*, *zdir='z'*, **args*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.bar)[¶](#mpl_toolkits.mplot3d.Axes3D.bar)
Add 2D bar(s).
---
Parameters:
left : 1D array-like
The x coordinates of the left sides of the bars.
height : 1D array-like
The height of the bars.
zs : scalar or 1D array-like
Z coordinate of bars; if a single value is specified, it will be
used for all bars.
zdir : {'x', 'y', 'z'}
When plotting 2D data, the direction to use as z ('x', 'y' or 'z');
defaults to 'z'.
**kwargs
Other arguments are forwarded to [matplotlib.axes.Axes.bar](https://matplotlib.org/../api/_as_gen/matplotlib.axes.Axes.bar.html#matplotlib.axes.Axes.bar).
Returns:
mpl_toolkits.mplot3d.art3d.Patch3DCollection
Bars3d
### Quiver
``Axes3D.````quiver``(*X*, *Y*, *Z*, *U*, *V*, *W*, */*, *length=1*, *arrow_length_ratio=.3*, *pivot='tail'*, *normalize=False*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.quiver)[¶](#mpl_toolkits.mplot3d.Axes3D.quiver)
Plot a 3D field of arrows.
The arguments could be array-like or scalars, so long as they
they can be broadcast together. The arguments can also be
masked arrays. If an element in any of argument is masked, then
that corresponding quiver element will not be plotted.
---
Parameters:
X, Y, Z : array-like
The x, y and z coordinates of the arrow locations (default is
tail of arrow; see pivot kwarg)
U, V, W : array-like
The x, y and z components of the arrow vectors
length : float
The length of each quiver, default to 1.0, the unit is
the same with the axes
arrow_length_ratio : float
The ratio of the arrow head with respect to the quiver,
default to 0.3
pivot : {'tail', 'middle', 'tip'}
The part of the arrow that is at the grid point; the arrow
rotates about this point, hence the name pivot.
Default is 'tail'
normalize : bool
When True, all of the arrows will be the same length. This
defaults to False, where the arrows will be different lengths
depending on the values of u,v,w.
**kwargs
Any additional keyword arguments are delegated to
[LineCollection](https://matplotlib.org/../api/collections_api.html#matplotlib.collections.LineCollection)
Quiver3d
### 2D plots in 3D
2dcollections3d
### Text
``Axes3D.````text``(*self*, *x*, *y*, *z*, *s*, *zdir=None*, ***kwargs*)[[source]](https://matplotlib.org_modules/mpl_toolkits/mplot3d/axes3d.html#Axes3D.text)[¶](#mpl_toolkits.mplot3d.Axes3D.text)
Add text to the plot. kwargs will be passed on to Axes.text,
except for the ``zdir`` keyword, which sets the direction to be
used as the z direction.
Text3d
### Subplotting
Having multiple 3D plots in a single figure is the same
as it is for 2D plots. Also, you can have both 2D and 3D plots
in the same figure.
*New in version 1.0.0:* Subplotting 3D plots was added in v1.0.0. Earlier version can not
do this.
Subplot3d
## Download
- [Download Python source code: mplot3d.py](https://matplotlib.org/_downloads/3227f29a1f1a9db7dd710eac0e54c41e/mplot3d.py)
- [Download Jupyter notebook: mplot3d.ipynb](https://matplotlib.org/_downloads/7105a36ab795ee5c5746ba7f95602c0d/mplot3d.ipynb)