Skip to content

Commit

Permalink
Docs build of 390e146c4d30025faf08eac0c9dba97b95dfc1e0
Browse files Browse the repository at this point in the history
  • Loading branch information
MatplotlibCircleBot authored and MatplotlibCircleBot committed Sep 16, 2024
1 parent c1b66f3 commit 16294a1
Show file tree
Hide file tree
Showing 13,398 changed files with 3,128,400 additions and 957,303 deletions.
The diff you're trying to view is too large. We only load the first 3000 changed files.
4 changes: 2 additions & 2 deletions .buildinfo
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Sphinx build info version 1
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
config: fee21aba0ad35d7353946075a94d4ae9
tags: 645f666f9bcd5a90fca523b33c5a78b7
config: 0db6e1c52bf6f073f4cc0d09bb384ce4
tags: 526838a1027dd1fd771fd21a9668211e
68 changes: 68 additions & 0 deletions _downloads/0017d0c84e03d6c5e463e23d8e570671/line_collection.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Plot multiple lines using a LineCollection\n\nMatplotlib can efficiently draw multiple lines at once using a `~.LineCollection`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.collections import LineCollection\n\ncolors = [\"indigo\", \"blue\", \"green\", \"yellow\", \"orange\", \"red\"]\n\n# create a list of half-circles with varying radii\ntheta = np.linspace(0, np.pi, 36)\nradii = np.linspace(4, 5, num=len(colors))\narcs = [np.column_stack([r * np.cos(theta), r * np.sin(theta)]) for r in radii]\n\nfig, ax = plt.subplots(figsize=(6.4, 3.2))\n# set axes limits manually because Collections do not take part in autoscaling\nax.set_xlim(-6, 6)\nax.set_ylim(0, 6)\nax.set_aspect(\"equal\") # to make the arcs look circular\n\n# create a LineCollection with the half-circles\n# its properties can be set per line by passing a sequence (here used for *colors*)\n# or they can be set for all lines by passing a scalar (here used for *linewidths*)\nline_collection = LineCollection(arcs, colors=colors, linewidths=4)\nax.add_collection(line_collection)\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Instead of passing a list of colors (``colors=colors``), we can alternatively use\ncolormapping. The lines are then color-coded based on an additional array of values\npassed to the *array* parameter. In the below example, we color the lines based on\ntheir radius by passing ``array=radii``.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"num_arcs = 15\ntheta = np.linspace(0, np.pi, 36)\nradii = np.linspace(4, 5.5, num=num_arcs)\narcs = [np.column_stack([r * np.cos(theta), r * np.sin(theta)]) for r in radii]\n\nfig, ax = plt.subplots(figsize=(6.4, 3))\n# set axes limits manually because Collections do not take part in autoscaling\nax.set_xlim(-6, 6)\nax.set_ylim(0, 6)\nax.set_aspect(\"equal\") # to make the arcs look circular\n\n# create a LineCollection with the half-circles and color mapping\nline_collection = LineCollection(arcs, array=radii, cmap=\"rainbow\")\nax.add_collection(line_collection)\n\nfig.colorbar(line_collection, label=\"Radius\")\nax.set_title(\"Line Collection with mapped colors\")\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.collections.LineCollection`\n - `matplotlib.collections.Collection.set_array`\n - `matplotlib.axes.Axes.add_collection`\n - `matplotlib.figure.Figure.colorbar` / `matplotlib.pyplot.colorbar`\n\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
266 changes: 266 additions & 0 deletions _downloads/0058fbe25cf21cd7c40fb5bd22f92895/axes_units.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n\n# Plotting dates and strings\n\nThe most basic way to use Matplotlib plotting methods is to pass coordinates in\nas numerical numpy arrays. For example, ``plot(x, y)`` will work if ``x`` and\n``y`` are numpy arrays of floats (or integers). Plotting methods will also\nwork if `numpy.asarray` will convert ``x`` and ``y`` to an array of floating\npoint numbers; e.g. ``x`` could be a python list.\n\nMatplotlib also has the ability to convert other data types if a \"unit\nconverter\" exists for the data type. Matplotlib has two built-in converters,\none for dates and the other for lists of strings. Other downstream libraries\nhave their own converters to handle their data types.\n\nThe method to add converters to Matplotlib is described in `matplotlib.units`.\nHere we briefly overview the built-in date and string converters.\n\n## Date conversion\n\nIf ``x`` and/or ``y`` are a list of `datetime` or an array of\n`numpy.datetime64`, Matplotlib has a built-in converter that will convert the\ndatetime to a float, and add tick locators and formatters to the axis that are\nappropriate for dates. See `matplotlib.dates`.\n\nIn the following example, the x-axis gains a converter that converts from\n`numpy.datetime64` to float, and a locator that put ticks at the beginning of\nthe month, and a formatter that label the ticks appropriately:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n\nimport matplotlib.dates as mdates\nimport matplotlib.units as munits\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')\ntime = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')\nx = np.arange(len(time))\nax.plot(time, x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that if we try to plot a float on the x-axis, it will be plotted in\nunits of days since the \"epoch\" for the converter, in this case 1970-01-01\n(see `date-format`). So when we plot the value 0, the ticks start at\n1970-01-01. (The locator also now chooses every two years for a tick instead\nof every month):\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')\ntime = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')\nx = np.arange(len(time))\nax.plot(time, x)\n# 0 gets labeled as 1970-01-01\nax.plot(0, 0, 'd')\nax.text(0, 0, ' Float x=0', rotation=45)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can customize the locator and the formatter; see `date-locators` and\n`date-formatters` for a complete list, and\n`date_formatters_locators` for examples of them in use. Here we locate\nby every second month, and format just with the month's 3-letter name using\n``\"%b\"`` (see `~datetime.datetime.strftime` for format codes):\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')\ntime = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')\nx = np.arange(len(time))\nax.plot(time, x)\nax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=np.arange(1, 13, 2)))\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))\nax.set_xlabel('1980')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The default locator is the `~.dates.AutoDateLocator`, and the default\nFormatter `~.dates.AutoDateFormatter`. There are also \"concise\" formatter\nand locators that give a more compact labelling, and can be set via rcParams.\nNote how instead of the redundant \"Jan\" label at the start of the year,\n\"1980\" is used instead. See `date_concise_formatter` for more examples.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"plt.rcParams['date.converter'] = 'concise'\n\nfig, ax = plt.subplots(figsize=(5.4, 2), layout='constrained')\ntime = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')\nx = np.arange(len(time))\nax.plot(time, x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can set the limits on the axis either by passing the appropriate dates as\nlimits, or by passing a floating-point value in the proper units of days\nsince the epoch. If we need it, we can get this value from\n`~.dates.date2num`.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, axs = plt.subplots(2, 1, figsize=(5.4, 3), layout='constrained')\nfor ax in axs.flat:\n time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')\n x = np.arange(len(time))\n ax.plot(time, x)\n\n# set xlim using datetime64:\naxs[0].set_xlim(np.datetime64('1980-02-01'), np.datetime64('1980-04-01'))\n\n# set xlim using floats:\n# Note can get from mdates.date2num(np.datetime64('1980-02-01'))\naxs[1].set_xlim(3683, 3683+60)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## String conversion: categorical plots\n\nSometimes we want to label categories on an axis rather than numbers.\nMatplotlib allows this using a \"categorical\" converter (see\n`~.matplotlib.category`).\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}\nnames = list(data.keys())\nvalues = list(data.values())\n\nfig, axs = plt.subplots(1, 3, figsize=(7, 3), sharey=True, layout='constrained')\naxs[0].bar(names, values)\naxs[1].scatter(names, values)\naxs[2].plot(names, values)\nfig.suptitle('Categorical Plotting')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the \"categories\" are plotted in the order that they are first\nspecified and that subsequent plotting in a different order will not affect\nthe original order. Further, new additions will be added on the end (see\n\"pear\" below):\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(5, 3), layout='constrained')\nax.bar(names, values)\n\n# plot in a different order:\nax.scatter(['lemon', 'apple'], [7, 12])\n\n# add a new category, \"pear\", and put the other categories in a different order:\nax.plot(['pear', 'orange', 'apple', 'lemon'], [13, 10, 7, 12], color='C1')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that when using ``plot`` like in the above, the order of the plotting is\nmapped onto the original order of the data, so the new line goes in the order\nspecified.\n\nThe category converter maps from categories to integers, starting at zero. So\ndata can also be manually added to the axis using a float. Note that if a\nfloat is passed in that does not have a \"category\" associated with it, the\ndata point can still be plotted, but a tick will not be created. In the\nfollowing, we plot data at 4.0 and 2.5, but no tick is added there because\nthose are not categories.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(5, 3), layout='constrained')\nax.bar(names, values)\n# arguments for styling the labels below:\nargs = {'rotation': 70, 'color': 'C1',\n 'bbox': {'color': 'white', 'alpha': .7, 'boxstyle': 'round'}}\n\n\n# 0 gets labeled as \"apple\"\nax.plot(0, 2, 'd', color='C1')\nax.text(0, 3, 'Float x=0', **args)\n\n# 2 gets labeled as \"lemon\"\nax.plot(2, 2, 'd', color='C1')\nax.text(2, 3, 'Float x=2', **args)\n\n# 4 doesn't get a label\nax.plot(4, 2, 'd', color='C1')\nax.text(4, 3, 'Float x=4', **args)\n\n# 2.5 doesn't get a label\nax.plot(2.5, 2, 'd', color='C1')\nax.text(2.5, 3, 'Float x=2.5', **args)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Setting the limits for a category axis can be done by specifying the\ncategories, or by specifying floating point numbers:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, axs = plt.subplots(2, 1, figsize=(5, 5), layout='constrained')\nax = axs[0]\nax.bar(names, values)\nax.set_xlim('orange', 'lemon')\nax.set_xlabel('limits set with categories')\nax = axs[1]\nax.bar(names, values)\nax.set_xlim(0.5, 2.5)\nax.set_xlabel('limits set with floats')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The category axes are helpful for some plot types, but can lead to confusion\nif data is read in as a list of strings, even if it is meant to be a list of\nfloats or dates. This sometimes happens when reading comma-separated value\n(CSV) files. The categorical locator and formatter will put a tick at every\nstring value and label each one as well:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(5.4, 2.5), layout='constrained')\nx = [str(xx) for xx in np.arange(100)] # list of strings\nax.plot(x, np.arange(100))\nax.set_xlabel('x is list of strings')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If this is not desired, then simply convert the data to floats before plotting:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(5.4, 2.5), layout='constrained')\nx = np.asarray(x, dtype='float') # array of float.\nax.plot(x, np.arange(100))\nax.set_xlabel('x is array of floats')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Determine converter, formatter, and locator on an axis\n\nSometimes it is helpful to be able to debug what Matplotlib is using to\nconvert the incoming data. We can do that by querying the ``converter``\nproperty on the axis. We can also query the formatters and locators using\n`~.axis.Axis.get_major_locator` and `~.axis.Axis.get_major_formatter`.\n\nNote that by default the converter is *None*.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, axs = plt.subplots(3, 1, figsize=(6.4, 7), layout='constrained')\nx = np.arange(100)\nax = axs[0]\nax.plot(x, x)\nlabel = f'Converter: {ax.xaxis.converter}\\n '\nlabel += f'Locator: {ax.xaxis.get_major_locator()}\\n'\nlabel += f'Formatter: {ax.xaxis.get_major_formatter()}\\n'\nax.set_xlabel(label)\n\nax = axs[1]\ntime = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]')\nx = np.arange(len(time))\nax.plot(time, x)\nlabel = f'Converter: {ax.xaxis.converter}\\n '\nlabel += f'Locator: {ax.xaxis.get_major_locator()}\\n'\nlabel += f'Formatter: {ax.xaxis.get_major_formatter()}\\n'\nax.set_xlabel(label)\n\nax = axs[2]\ndata = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}\nnames = list(data.keys())\nvalues = list(data.values())\nax.plot(names, values)\nlabel = f'Converter: {ax.xaxis.converter}\\n '\nlabel += f'Locator: {ax.xaxis.get_major_locator()}\\n'\nlabel += f'Formatter: {ax.xaxis.get_major_formatter()}\\n'\nax.set_xlabel(label)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## More about \"unit\" support\n\nThe support for dates and categories is part of \"units\" support that is built\ninto Matplotlib. This is described at `.matplotlib.units` and in the\n`basic_units` example.\n\nUnit support works by querying the type of data passed to the plotting\nfunction and dispatching to the first converter in a list that accepts that\ntype of data. So below, if ``x`` has ``datetime`` objects in it, the\nconverter will be ``_SwitchableDateConverter``; if it has has strings in it,\nit will be sent to the ``StrCategoryConverter``.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for k, v in munits.registry.items():\n print(f\"type: {k};\\n converter: {type(v)}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are a number of downstream libraries that provide their own converters\nwith locators and formatters. Physical unit support is provided by\n[astropy](https://www.astropy.org), [pint](https://pint.readthedocs.io), and\n[unyt](https://unyt.readthedocs.io), among others.\n\nHigh level libraries like [pandas](https://pandas.pydata.org) and\n[nc-time-axis](https://nc-time-axis.readthedocs.io) (and thus\n[xarray](https://docs.xarray.dev)) provide their own datetime support.\nThis support can sometimes be incompatible with Matplotlib native datetime\nsupport, so care should be taken when using Matplotlib locators and\nformatters if these libraries are being used.\n\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
29 changes: 29 additions & 0 deletions _downloads/008c73d5ac1c4af82c0b90fde922ebb9/stairs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
==============
stairs(values)
==============
Draw a stepwise constant function as a line or a filled plot.
See `~matplotlib.axes.Axes.stairs` when plotting :math:`y` between
:math:`(x_i, x_{i+1})`. For plotting :math:`y` at :math:`x`, see
`~matplotlib.axes.Axes.step`.
.. redirect-from:: /plot_types/basic/step
"""
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('_mpl-gallery')

# make data
y = [4.8, 5.5, 3.5, 4.6, 6.5, 6.6, 2.6, 3.0]

# plot
fig, ax = plt.subplots()

ax.stairs(y, linewidth=2.5)

ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
ylim=(0, 8), yticks=np.arange(1, 8))

plt.show()
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
x = np.linspace(1., 3., 10)
y = x**3

fig, ax = plt.subplots()
ax.plot(x, y, linestyle='--', color='orange', gapcolor='blue',
linewidth=3, label='a striped line')
ax.legend()
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading

0 comments on commit 16294a1

Please sign in to comment.