{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n.. redirect-from:: /tutorials/intermediate/artists\n\n\n# Artist tutorial\n\nUsing Artist objects to render on the canvas.\n\nThere are three layers to the Matplotlib API.\n\n* the :class:`!matplotlib.backend_bases.FigureCanvas` is the area onto which\n the figure is drawn\n* the :class:`!matplotlib.backend_bases.Renderer` is the object which knows how\n to draw on the :class:`!matplotlib.backend_bases.FigureCanvas`\n* and the :class:`matplotlib.artist.Artist` is the object that knows how to use\n a renderer to paint onto the canvas.\n\nThe :class:`!matplotlib.backend_bases.FigureCanvas` and\n:class:`!matplotlib.backend_bases.Renderer` handle all the details of\ntalking to user interface toolkits like [wxPython](https://www.wxpython.org) or drawing languages like PostScript\u00ae, and\nthe ``Artist`` handles all the high level constructs like representing\nand laying out the figure, text, and lines. The typical user will\nspend 95% of their time working with the ``Artists``.\n\nThere are two types of ``Artists``: primitives and containers. The primitives\nrepresent the standard graphical objects we want to paint onto our canvas:\n:class:`~matplotlib.lines.Line2D`, :class:`~matplotlib.patches.Rectangle`,\n:class:`~matplotlib.text.Text`, :class:`~matplotlib.image.AxesImage`, etc., and\nthe containers are places to put them (:class:`~matplotlib.axis.Axis`,\n:class:`~matplotlib.axes.Axes` and :class:`~matplotlib.figure.Figure`). The\nstandard use is to create a :class:`~matplotlib.figure.Figure` instance, use\nthe ``Figure`` to create one or more :class:`~matplotlib.axes.Axes`\ninstances, and use the ``Axes`` instance\nhelper methods to create the primitives. In the example below, we create a\n``Figure`` instance using :func:`matplotlib.pyplot.figure`, which is a\nconvenience method for instantiating ``Figure`` instances and connecting them\nwith your user interface or drawing toolkit ``FigureCanvas``. As we will\ndiscuss below, this is not necessary -- you can work directly with PostScript,\nPDF Gtk+, or wxPython ``FigureCanvas`` instances, instantiate your ``Figures``\ndirectly and connect them yourselves -- but since we are focusing here on the\n``Artist`` API we'll let :mod:`~matplotlib.pyplot` handle some of those details\nfor us::\n\n import matplotlib.pyplot as plt\n fig = plt.figure()\n ax = fig.add_subplot(2, 1, 1) # two rows, one column, first plot\n\nThe :class:`~matplotlib.axes.Axes` is probably the most important\nclass in the Matplotlib API, and the one you will be working with most\nof the time. This is because the ``Axes`` is the plotting area into\nwhich most of the objects go, and the ``Axes`` has many special helper\nmethods (:meth:`~matplotlib.axes.Axes.plot`,\n:meth:`~matplotlib.axes.Axes.text`,\n:meth:`~matplotlib.axes.Axes.hist`,\n:meth:`~matplotlib.axes.Axes.imshow`) to create the most common\ngraphics primitives (:class:`~matplotlib.lines.Line2D`,\n:class:`~matplotlib.text.Text`,\n:class:`~matplotlib.patches.Rectangle`,\n:class:`~matplotlib.image.AxesImage`, respectively). These helper methods\nwill take your data (e.g., ``numpy`` arrays and strings) and create\nprimitive ``Artist`` instances as needed (e.g., ``Line2D``), add them to\nthe relevant containers, and draw them when requested. If you want to create\nan ``Axes`` at an arbitrary location, simply use the\n:meth:`~matplotlib.figure.Figure.add_axes` method which takes a list\nof ``[left, bottom, width, height]`` values in 0-1 relative figure\ncoordinates::\n\n fig2 = plt.figure()\n ax2 = fig2.add_axes([0.15, 0.1, 0.7, 0.3])\n\nContinuing with our example::\n\n import numpy as np\n t = np.arange(0.0, 1.0, 0.01)\n s = np.sin(2*np.pi*t)\n line, = ax.plot(t, s, color='blue', lw=2)\n\nIn this example, ``ax`` is the ``Axes`` instance created by the\n``fig.add_subplot`` call above and when you call ``ax.plot``, it creates a\n``Line2D`` instance and\nadds it to the ``Axes``. In the interactive [IPython](https://ipython.org/)\nsession below, you can see that the ``Axes.lines`` list is length one and\ncontains the same line that was returned by the ``line, = ax.plot...`` call:\n\n.. sourcecode:: ipython\n\n In [101]: ax.lines[0]\n Out[101]: \n\n In [102]: line\n Out[102]: \n\nIf you make subsequent calls to ``ax.plot`` (and the hold state is \"on\"\nwhich is the default) then additional lines will be added to the list.\nYou can remove a line later by calling its ``remove`` method::\n\n line = ax.lines[0]\n line.remove()\n\nThe Axes also has helper methods to configure and decorate the x-axis\nand y-axis tick, tick labels and axis labels::\n\n xtext = ax.set_xlabel('my xdata') # returns a Text instance\n ytext = ax.set_ylabel('my ydata')\n\nWhen you call :meth:`ax.set_xlabel `,\nit passes the information on the :class:`~matplotlib.text.Text`\ninstance of the :class:`~matplotlib.axis.XAxis`. Each ``Axes``\ninstance contains an :class:`~matplotlib.axis.XAxis` and a\n:class:`~matplotlib.axis.YAxis` instance, which handle the layout and\ndrawing of the ticks, tick labels and axis labels.\n\nTry creating the figure below.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nfig.subplots_adjust(top=0.8)\nax1 = fig.add_subplot(211)\nax1.set_ylabel('Voltage [V]')\nax1.set_title('A sine wave')\n\nt = np.arange(0.0, 1.0, 0.01)\ns = np.sin(2*np.pi*t)\nline, = ax1.plot(t, s, color='blue', lw=2)\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\nax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])\nn, bins, patches = ax2.hist(np.random.randn(1000), 50,\n facecolor='yellow', edgecolor='yellow')\nax2.set_xlabel('Time [s]')\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n## Customizing your objects\n\nEvery element in the figure is represented by a Matplotlib\n:class:`~matplotlib.artist.Artist`, and each has an extensive list of\nproperties to configure its appearance. The figure itself contains a\n:class:`~matplotlib.patches.Rectangle` exactly the size of the figure,\nwhich you can use to set the background color and transparency of the\nfigures. Likewise, each :class:`~matplotlib.axes.Axes` bounding box\n(the standard white box with black edges in the typical Matplotlib\nplot, has a ``Rectangle`` instance that determines the color,\ntransparency, and other properties of the Axes. These instances are\nstored as member variables :attr:`!Figure.patch` and :attr:`!Axes.patch`\n(\"Patch\" is a name inherited from MATLAB, and is a 2D \"patch\"\nof color on the figure, e.g., rectangles, circles and polygons).\nEvery Matplotlib ``Artist`` has the following properties\n\n========== =================================================================\nProperty Description\n========== =================================================================\nalpha The transparency - a scalar from 0-1\nanimated A boolean that is used to facilitate animated drawing\naxes The Axes that the Artist lives in, possibly None\nclip_box The bounding box that clips the Artist\nclip_on Whether clipping is enabled\nclip_path The path the artist is clipped to\ncontains A picking function to test whether the artist contains the pick\n point\nfigure The figure instance the artist lives in, possibly None\nlabel A text label (e.g., for auto-labeling)\npicker A python object that controls object picking\ntransform The transformation\nvisible A boolean whether the artist should be drawn\nzorder A number which determines the drawing order\nrasterized Boolean; Turns vectors into raster graphics (for compression &\n EPS transparency)\n========== =================================================================\n\nEach of the properties is accessed with an old-fashioned setter or\ngetter (yes we know this irritates Pythonistas and we plan to support\ndirect access via properties or traits but it hasn't been done yet).\nFor example, to multiply the current alpha by a half::\n\n a = o.get_alpha()\n o.set_alpha(0.5*a)\n\nIf you want to set a number of properties at once, you can also use\nthe ``set`` method with keyword arguments. For example::\n\n o.set(alpha=0.5, zorder=2)\n\nIf you are working interactively at the python shell, a handy way to\ninspect the ``Artist`` properties is to use the\n:func:`matplotlib.artist.getp` function (simply\n:func:`~matplotlib.pyplot.getp` in pyplot), which lists the properties\nand their values. This works for classes derived from ``Artist`` as\nwell, e.g., ``Figure`` and ``Rectangle``. Here are the ``Figure`` rectangle\nproperties mentioned above:\n\n.. sourcecode:: ipython\n\n In [149]: matplotlib.artist.getp(fig.patch)\n agg_filter = None\n alpha = None\n animated = False\n antialiased or aa = False\n bbox = Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0)\n capstyle = butt\n children = []\n clip_box = None\n clip_on = True\n clip_path = None\n contains = None\n data_transform = BboxTransformTo( TransformedBbox( Bbox...\n edgecolor or ec = (1.0, 1.0, 1.0, 1.0)\n extents = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0)\n facecolor or fc = (1.0, 1.0, 1.0, 1.0)\n figure = Figure(640x480)\n fill = True\n gid = None\n hatch = None\n height = 1\n in_layout = False\n joinstyle = miter\n label =\n linestyle or ls = solid\n linewidth or lw = 0.0\n patch_transform = CompositeGenericTransform( BboxTransformTo( ...\n path = Path(array([[0., 0.], [1., 0.], [1.,...\n path_effects = []\n picker = None\n rasterized = None\n sketch_params = None\n snap = None\n transform = CompositeGenericTransform( CompositeGenericTra...\n transformed_clip_path_and_affine = (None, None)\n url = None\n verts = [[ 0. 0.] [640. 0.] [640. 480.] [ 0. 480....\n visible = True\n width = 1\n window_extent = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0)\n x = 0\n xy = (0, 0)\n y = 0\n zorder = 1\n\nThe docstrings for all of the classes also contain the ``Artist``\nproperties, so you can consult the interactive \"help\" or the\n`artist-api` for a listing of properties for a given object.\n\n\n## Object containers\n\n\nNow that we know how to inspect and set the properties of a given\nobject we want to configure, we need to know how to get at that object.\nAs mentioned in the introduction, there are two kinds of objects:\nprimitives and containers. The primitives are usually the things you\nwant to configure (the font of a :class:`~matplotlib.text.Text`\ninstance, the width of a :class:`~matplotlib.lines.Line2D`) although\nthe containers also have some properties as well -- for example the\n:class:`~matplotlib.axes.Axes` :class:`~matplotlib.artist.Artist` is a\ncontainer that contains many of the primitives in your plot, but it\nalso has properties like the ``xscale`` to control whether the xaxis\nis 'linear' or 'log'. In this section we'll review where the various\ncontainer objects store the ``Artists`` that you want to get at.\n\n\n### Figure container\n\nThe top level container ``Artist`` is the\n:class:`matplotlib.figure.Figure`, and it contains everything in the\nfigure. The background of the figure is a\n:class:`~matplotlib.patches.Rectangle` which is stored in\n:attr:`!Figure.patch`. As\nyou add subplots (:meth:`~matplotlib.figure.Figure.add_subplot`) and\nAxes (:meth:`~matplotlib.figure.Figure.add_axes`) to the figure\nthese will be appended to the :attr:`Figure.axes\n`. These are also returned by the\nmethods that create them:\n\n.. sourcecode:: ipython\n\n In [156]: fig = plt.figure()\n\n In [157]: ax1 = fig.add_subplot(211)\n\n In [158]: ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3])\n\n In [159]: ax1\n Out[159]: \n\n In [160]: print(fig.axes)\n [, ]\n\nBecause the figure maintains the concept of the \"current Axes\" (see\n:meth:`Figure.gca ` and\n:meth:`Figure.sca `) to support the\npylab/pyplot state machine, you should not insert or remove Axes\ndirectly from the Axes list, but rather use the\n:meth:`~matplotlib.figure.Figure.add_subplot` and\n:meth:`~matplotlib.figure.Figure.add_axes` methods to insert, and the\n`Axes.remove ` method to delete. You are\nfree however, to iterate over the list of Axes or index into it to get\naccess to ``Axes`` instances you want to customize. Here is an\nexample which turns all the Axes grids on::\n\n for ax in fig.axes:\n ax.grid(True)\n\n\nThe figure also has its own ``images``, ``lines``, ``patches`` and ``text``\nattributes, which you can use to add primitives directly. When doing so, the\ndefault coordinate system for the ``Figure`` will simply be in pixels (which\nis not usually what you want). If you instead use Figure-level methods to add\nArtists (e.g., using `.Figure.text` to add text), then the default coordinate\nsystem will be \"figure coordinates\" where (0, 0) is the bottom-left of the\nfigure and (1, 1) is the top-right of the figure.\n\nAs with all ``Artist``\\s, you can control this coordinate system by setting\nthe transform property. You can explicitly use \"figure coordinates\" by\nsetting the ``Artist`` transform to :attr:`!fig.transFigure`:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.lines as lines\n\nfig = plt.figure()\n\nl1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig)\nl2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig)\nfig.lines.extend([l1, l2])\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a summary of the Artists the Figure contains\n\n================ ============================================================\nFigure attribute Description\n================ ============================================================\naxes A list of `~.axes.Axes` instances\npatch The `.Rectangle` background\nimages A list of `.FigureImage` patches -\n useful for raw pixel display\nlegends A list of Figure `.Legend` instances\n (different from ``Axes.get_legend()``)\nlines A list of Figure `.Line2D` instances\n (rarely used, see ``Axes.lines``)\npatches A list of Figure `.Patch`\\s\n (rarely used, see ``Axes.patches``)\ntexts A list Figure `.Text` instances\n================ ============================================================\n\n\n### Axes container\n\nThe :class:`matplotlib.axes.Axes` is the center of the Matplotlib\nuniverse -- it contains the vast majority of all the ``Artists`` used\nin a figure with many helper methods to create and add these\n``Artists`` to itself, as well as helper methods to access and\ncustomize the ``Artists`` it contains. Like the\n:class:`~matplotlib.figure.Figure`, it contains a\n:class:`~matplotlib.patches.Patch`\n:attr:`!matplotlib.axes.Axes.patch` which is a\n:class:`~matplotlib.patches.Rectangle` for Cartesian coordinates and a\n:class:`~matplotlib.patches.Circle` for polar coordinates; this patch\ndetermines the shape, background and border of the plotting region::\n\n ax = fig.add_subplot()\n rect = ax.patch # a Rectangle instance\n rect.set_facecolor('green')\n\nWhen you call a plotting method, e.g., the canonical\n`~matplotlib.axes.Axes.plot` and pass in arrays or lists of values, the\nmethod will create a `matplotlib.lines.Line2D` instance, update the line with\nall the ``Line2D`` properties passed as keyword arguments, add the line to\nthe ``Axes``, and return it to you:\n\n.. sourcecode:: ipython\n\n In [213]: x, y = np.random.rand(2, 100)\n\n In [214]: line, = ax.plot(x, y, '-', color='blue', linewidth=2)\n\n``plot`` returns a list of lines because you can pass in multiple x, y\npairs to plot, and we are unpacking the first element of the length\none list into the line variable. The line has been added to the\n``Axes.lines`` list:\n\n.. sourcecode:: ipython\n\n In [229]: print(ax.lines)\n []\n\nSimilarly, methods that create patches, like\n:meth:`~matplotlib.axes.Axes.bar` creates a list of rectangles, will\nadd the patches to the :attr:`!Axes.patches` list:\n\n.. sourcecode:: ipython\n\n In [233]: n, bins, rectangles = ax.hist(np.random.randn(1000), 50)\n\n In [234]: rectangles\n Out[234]: \n\n In [235]: print(len(ax.patches))\n Out[235]: 50\n\nYou should not add objects directly to the ``Axes.lines`` or ``Axes.patches``\nlists, because the ``Axes`` needs to do a few things when it creates and adds\nan object:\n\n- It sets the ``figure`` and ``axes`` property of the ``Artist``;\n- It sets the default ``Axes`` transformation (unless one is already set);\n- It inspects the data contained in the ``Artist`` to update the data\n structures controlling auto-scaling, so that the view limits can be\n adjusted to contain the plotted data.\n\nYou can, nonetheless, create objects yourself and add them directly to the\n``Axes`` using helper methods like `~matplotlib.axes.Axes.add_line` and\n`~matplotlib.axes.Axes.add_patch`. Here is an annotated interactive session\nillustrating what is going on:\n\n.. sourcecode:: ipython\n\n In [262]: fig, ax = plt.subplots()\n\n # create a rectangle instance\n In [263]: rect = matplotlib.patches.Rectangle((1, 1), width=5, height=12)\n\n # by default the Axes instance is None\n In [264]: print(rect.axes)\n None\n\n # and the transformation instance is set to the \"identity transform\"\n In [265]: print(rect.get_data_transform())\n IdentityTransform()\n\n # now we add the Rectangle to the Axes\n In [266]: ax.add_patch(rect)\n\n # and notice that the ax.add_patch method has set the Axes\n # instance\n In [267]: print(rect.axes)\n Axes(0.125,0.1;0.775x0.8)\n\n # and the transformation has been set too\n In [268]: print(rect.get_data_transform())\n CompositeGenericTransform(\n TransformWrapper(\n BlendedAffine2D(\n IdentityTransform(),\n IdentityTransform())),\n CompositeGenericTransform(\n BboxTransformFrom(\n TransformedBbox(\n Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0),\n TransformWrapper(\n BlendedAffine2D(\n IdentityTransform(),\n IdentityTransform())))),\n BboxTransformTo(\n TransformedBbox(\n Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),\n BboxTransformTo(\n TransformedBbox(\n Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),\n Affine2D(\n [[100. 0. 0.]\n [ 0. 100. 0.]\n [ 0. 0. 1.]])))))))\n\n # the default Axes transformation is ax.transData\n In [269]: print(ax.transData)\n CompositeGenericTransform(\n TransformWrapper(\n BlendedAffine2D(\n IdentityTransform(),\n IdentityTransform())),\n CompositeGenericTransform(\n BboxTransformFrom(\n TransformedBbox(\n Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0),\n TransformWrapper(\n BlendedAffine2D(\n IdentityTransform(),\n IdentityTransform())))),\n BboxTransformTo(\n TransformedBbox(\n Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),\n BboxTransformTo(\n TransformedBbox(\n Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),\n Affine2D(\n [[100. 0. 0.]\n [ 0. 100. 0.]\n [ 0. 0. 1.]])))))))\n\n # notice that the xlimits of the Axes have not been changed\n In [270]: print(ax.get_xlim())\n (0.0, 1.0)\n\n # but the data limits have been updated to encompass the rectangle\n In [271]: print(ax.dataLim.bounds)\n (1.0, 1.0, 5.0, 12.0)\n\n # we can manually invoke the auto-scaling machinery\n In [272]: ax.autoscale_view()\n\n # and now the xlim are updated to encompass the rectangle, plus margins\n In [273]: print(ax.get_xlim())\n (0.75, 6.25)\n\n # we have to manually force a figure draw\n In [274]: fig.canvas.draw()\n\n\nThere are many, many ``Axes`` helper methods for creating primitive\n``Artists`` and adding them to their respective containers. The table\nbelow summarizes a small sampling of them, the kinds of ``Artist`` they\ncreate, and where they store them\n\n========================================= ================= ===============\nAxes helper method Artist Container\n========================================= ================= ===============\n`~.axes.Axes.annotate` - text annotations `.Annotation` ax.texts\n`~.axes.Axes.bar` - bar charts `.Rectangle` ax.patches\n`~.axes.Axes.errorbar` - error bar plots `.Line2D` and ax.lines and\n `.Rectangle` ax.patches\n`~.axes.Axes.fill` - shared area `.Polygon` ax.patches\n`~.axes.Axes.hist` - histograms `.Rectangle` ax.patches\n`~.axes.Axes.imshow` - image data `.AxesImage` ax.images\n`~.axes.Axes.legend` - Axes legend `.Legend` ax.get_legend()\n`~.axes.Axes.plot` - xy plots `.Line2D` ax.lines\n`~.axes.Axes.scatter` - scatter charts `.PolyCollection` ax.collections\n`~.axes.Axes.text` - text `.Text` ax.texts\n========================================= ================= ===============\n\n\nIn addition to all of these ``Artists``, the ``Axes`` contains two\nimportant ``Artist`` containers: the :class:`~matplotlib.axis.XAxis`\nand :class:`~matplotlib.axis.YAxis`, which handle the drawing of the\nticks and labels. These are stored as instance variables\n:attr:`!matplotlib.axes.Axes.xaxis` and\n:attr:`!matplotlib.axes.Axes.yaxis`. The ``XAxis`` and ``YAxis``\ncontainers will be detailed below, but note that the ``Axes`` contains\nmany helper methods which forward calls on to the\n:class:`~matplotlib.axis.Axis` instances, so you often do not need to\nwork with them directly unless you want to. For example, you can set\nthe font color of the ``XAxis`` ticklabels using the ``Axes`` helper\nmethod::\n\n ax.tick_params(axis='x', labelcolor='orange')\n\nBelow is a summary of the Artists that the `~.axes.Axes` contains\n\n============== =========================================\nAxes attribute Description\n============== =========================================\nartists An `.ArtistList` of `.Artist` instances\npatch `.Rectangle` instance for Axes background\ncollections An `.ArtistList` of `.Collection` instances\nimages An `.ArtistList` of `.AxesImage`\nlines An `.ArtistList` of `.Line2D` instances\npatches An `.ArtistList` of `.Patch` instances\ntexts An `.ArtistList` of `.Text` instances\nxaxis A `matplotlib.axis.XAxis` instance\nyaxis A `matplotlib.axis.YAxis` instance\n============== =========================================\n\nThe legend can be accessed by `~.axes.Axes.get_legend`,\n\n\n### Axis containers\n\nThe :class:`matplotlib.axis.Axis` instances handle the drawing of the\ntick lines, the grid lines, the tick labels and the axis label. You\ncan configure the left and right ticks separately for the y-axis, and\nthe upper and lower ticks separately for the x-axis. The ``Axis``\nalso stores the data and view intervals used in auto-scaling, panning\nand zooming, as well as the :class:`~matplotlib.ticker.Locator` and\n:class:`~matplotlib.ticker.Formatter` instances which control where\nthe ticks are placed and how they are represented as strings.\n\nEach ``Axis`` object contains a :attr:`~matplotlib.axis.Axis.label` attribute\n(this is what :mod:`.pyplot` modifies in calls to `~.pyplot.xlabel` and\n`~.pyplot.ylabel`) as well as a list of major and minor ticks. The ticks are\n`.axis.XTick` and `.axis.YTick` instances, which contain the actual line and\ntext primitives that render the ticks and ticklabels. Because the ticks are\ndynamically created as needed (e.g., when panning and zooming), you should\naccess the lists of major and minor ticks through their accessor methods\n`.axis.Axis.get_major_ticks` and `.axis.Axis.get_minor_ticks`. Although\nthe ticks contain all the primitives and will be covered below, ``Axis``\ninstances have accessor methods that return the tick lines, tick labels, tick\nlocations etc.:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\naxis = ax.xaxis\naxis.get_ticklocs()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"axis.get_ticklabels()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"note there are twice as many ticklines as labels because by default there are\ntick lines at the top and bottom but only tick labels below the xaxis;\nhowever, this can be customized.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"axis.get_ticklines()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And with the above methods, you only get lists of major ticks back by\ndefault, but you can also ask for the minor ticks:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"axis.get_ticklabels(minor=True)\naxis.get_ticklines(minor=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a summary of some of the useful accessor methods of the ``Axis``\n(these have corresponding setters where useful, such as\n:meth:`~matplotlib.axis.Axis.set_major_formatter`.)\n\n============================= ==============================================\nAxis accessor method Description\n============================= ==============================================\n`~.Axis.get_scale` The scale of the Axis, e.g., 'log' or 'linear'\n`~.Axis.get_view_interval` The interval instance of the Axis view limits\n`~.Axis.get_data_interval` The interval instance of the Axis data limits\n`~.Axis.get_gridlines` A list of grid lines for the Axis\n`~.Axis.get_label` The Axis label - a `.Text` instance\n`~.Axis.get_offset_text` The Axis offset text - a `.Text` instance\n`~.Axis.get_ticklabels` A list of `.Text` instances -\n keyword minor=True|False\n`~.Axis.get_ticklines` A list of `.Line2D` instances -\n keyword minor=True|False\n`~.Axis.get_ticklocs` A list of Tick locations -\n keyword minor=True|False\n`~.Axis.get_major_locator` The `.ticker.Locator` instance for major ticks\n`~.Axis.get_major_formatter` The `.ticker.Formatter` instance for major\n ticks\n`~.Axis.get_minor_locator` The `.ticker.Locator` instance for minor ticks\n`~.Axis.get_minor_formatter` The `.ticker.Formatter` instance for minor\n ticks\n`~.axis.Axis.get_major_ticks` A list of `.Tick` instances for major ticks\n`~.axis.Axis.get_minor_ticks` A list of `.Tick` instances for minor ticks\n`~.Axis.grid` Turn the grid on or off for the major or minor\n ticks\n============================= ==============================================\n\nHere is an example, not recommended for its beauty, which customizes\nthe Axes and Tick properties.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# plt.figure creates a matplotlib.figure.Figure instance\nfig = plt.figure()\nrect = fig.patch # a rectangle instance\nrect.set_facecolor('lightgoldenrodyellow')\n\nax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4])\nrect = ax1.patch\nrect.set_facecolor('lightslategray')\n\n\nfor label in ax1.xaxis.get_ticklabels():\n # label is a Text instance\n label.set_color('red')\n label.set_rotation(45)\n label.set_fontsize(16)\n\nfor line in ax1.yaxis.get_ticklines():\n # line is a Line2D instance\n line.set_color('green')\n line.set_markersize(25)\n line.set_markeredgewidth(3)\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n### Tick containers\n\nThe :class:`matplotlib.axis.Tick` is the final container object in our\ndescent from the :class:`~matplotlib.figure.Figure` to the\n:class:`~matplotlib.axes.Axes` to the :class:`~matplotlib.axis.Axis`\nto the :class:`~matplotlib.axis.Tick`. The ``Tick`` contains the tick\nand grid line instances, as well as the label instances for the upper\nand lower ticks. Each of these is accessible directly as an attribute\nof the ``Tick``.\n\n============== ==========================================================\nTick attribute Description\n============== ==========================================================\ntick1line A `.Line2D` instance\ntick2line A `.Line2D` instance\ngridline A `.Line2D` instance\nlabel1 A `.Text` instance\nlabel2 A `.Text` instance\n============== ==========================================================\n\nHere is an example which sets the formatter for the right side ticks with\ndollar signs and colors them green on the right side of the yaxis.\n\n\n.. include:: ../gallery/ticks/dollar_ticks.rst\n :start-after: .. redirect-from:: /gallery/pyplots/dollar_ticks\n :end-before: .. admonition:: References\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.13.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}