- Add a title and axis labels to your charts using matplotlib
- matplotlib.axes #
- The Axes class#
- Plotting#
- Basic#
- Spans#
- Spectral#
- Statistics#
- Binned#
- Contours#
- 2D arrays#
- Unstructured triangles#
- Text and annotations#
- Vector fields#
- Clearing#
- Appearance#
- Property cycle#
- Axis / limits#
- Axis limits and direction#
- Axis labels, title, and legend#
- Axis scales#
- Autoscaling and margins#
- Aspect ratio#
- Ticks and tick labels#
- Units#
- Adding artists#
- Twinning and sharing#
- Axes position#
- Async/event based#
- Interactive#
- Children#
- Drawing#
- Projection#
- Other#
Add a title and axis labels to your charts using matplotlib
In this post, you will see how to add a title and axis labels to your python charts using matplotlib. If you’re new to python and want to get the basics of matplotlib , this online course can be interesting.
In the following example, title, x label and y label are added to the barplot using the title() , xlabel() , and ylabel() functions of the matplotlib library.
Those functions are applied to a barplot in the example, but the same method would work for other chart types.
# libraries import numpy as np import matplotlib.pyplot as plt # create dataset height = [3, 12, 5, 18, 45] bars = ('A', 'B', 'C', 'D', 'E') x_pos = np.arange(len(bars)) # Create bars and choose color plt.bar(x_pos, height, color = (0.5,0.1,0.5,0.6)) # Add title and axis names plt.title('My title') plt.xlabel('categories') plt.ylabel('values') # Create names on the x axis plt.xticks(x_pos, bars) # Show graph plt.show()
Note: the matplotlib section provides a lot of tips and tricks on how to customize a matplotlib chart!
matplotlib.axes #
The Axes class represents one (sub-)plot in a figure. It contains the plotted data, axis ticks, labels, title, legend, etc. Its methods are the main interface for manipulating the plot.
The Axes class#
An Axes object encapsulates all the elements of an individual (sub-)plot in a figure.
Plotting#
Basic#
Plot y versus x as lines and/or markers.
Plot y versus x as lines and/or markers with attached errorbars.
[Discouraged] Plot coercing the axis to treat floats as dates.Make a plot with log scaling on both the x- and y-axis.
Make a plot with log scaling on the x-axis.
Make a plot with log scaling on the y-axis.
Fill the area between two horizontal curves.
Fill the area between two vertical curves.
Make a horizontal bar plot.
Plot identical parallel lines at the given positions.
Plot a horizontal sequence of rectangles.
Plot vertical lines at each x from ymin to ymax.
Plot horizontal lines at each y from xmin to xmax.
Spans#
Add a horizontal line across the Axes.
Add a horizontal span (rectangle) across the Axes.
Add a vertical line across the Axes.
Add a vertical span (rectangle) across the Axes.
Add an infinitely long straight line.
Spectral#
Plot the autocorrelation of x.
Plot the coherence between x and y.
Plot the cross-spectral density.
Plot the magnitude spectrum.
Plot the power spectral density.
Plot the cross correlation between x and y.
Statistics#
Draw a box and whisker plot.
Drawing function for violin plots.
Drawing function for box and whisker plots.
Binned#
Make a 2D hexagonal binning plot of points x, y.
Compute and plot a histogram.
A stepwise constant function as a line with bounding edges or a filled plot.
Contours#
2D arrays#
Display data as an image, i.e., on a 2D regular raster.
Plot the values of a 2D matrix or array as color-coded image.
Create a pseudocolor plot with a non-regular rectangular grid.
Create a pseudocolor plot with a non-regular rectangular grid.
Create a pseudocolor plot with a non-regular rectangular grid.
Plot the sparsity pattern of a 2D array.
Unstructured triangles#
Create a pseudocolor plot of an unstructured triangular grid.
Draw an unstructured triangular grid as lines and/or markers.
Draw contour lines on an unstructured triangular grid.
Draw contour regions on an unstructured triangular grid.
Text and annotations#
Annotate the point xy with text text.
Add a child inset Axes to this existing Axes.
Add an inset indicator to the Axes.
Add an inset indicator rectangle to the Axes based on the axis limits for an inset_ax and draw connectors between inset_ax and the rectangle.
Add a second x-axis to this Axes .
Add a second y-axis to this Axes .
Vector fields#
Plot a 2D field of arrows.
Add a key to a quiver plot.
Draw streamlines of a vector flow.
Clearing#
Appearance#
Convenience method to get or set some axis properties.
Set whether the Axes rectangle patch is drawn.
Get whether the Axes rectangle patch is drawn.
Set whether axis ticks and gridlines are above or below most artists.
Get whether axis ticks and gridlines are above or below most artists.
Get the facecolor of the Axes.
Set the facecolor of the Axes.
Property cycle#
Set the property cycle of the Axes.
Axis / limits#
[Discouraged] Return the XAxis instance. [Discouraged] Return the YAxis instance.Axis limits and direction#
Return whether the xaxis is oriented in the «inverse» direction.
Return whether the yaxis is oriented in the «inverse» direction.
Set the x-axis view limits.
Return the x-axis view limits.
Set the y-axis view limits.
Return the y-axis view limits.
Extend the dataLim Bbox to include the given points.
Set the lower and upper numerical bounds of the x-axis.
Return the lower and upper x-axis bounds, in increasing order.
Set the lower and upper numerical bounds of the y-axis.
Return the lower and upper y-axis bounds, in increasing order.
Axis labels, title, and legend#
Set the label for the x-axis.
Get the xlabel text string.
Set the label for the y-axis.
Get the ylabel text string.
Only show «outer» labels and tick labels.
Place a legend on the Axes.
Return the Legend instance, or None if no legend is defined.
Return handles and labels for legend
Axis scales#
Return the xaxis’ scale (as a str).
Return the yaxis’ scale (as a str).
Autoscaling and margins#
When autoscaling, whether to obey all Artist.sticky_edges .
Set or retrieve autoscaling margins.
Set padding of X data limits prior to autoscaling.
Set padding of Y data limits prior to autoscaling.
Recompute the data limits based on current artists.
Autoscale the axis view to the data (toggle).
Autoscale the view limits using the data limits.
Set whether autoscaling is applied to each axis on the next draw or call to Axes.autoscale_view .
Return True if each axis is autoscaled, False otherwise.
Set whether the xaxis is autoscaled when drawing or by Axes.autoscale_view .
Return whether the xaxis is autoscaled.
Set whether the yaxis is autoscaled when drawing or by Axes.autoscale_view .
Return whether the yaxis is autoscaled.
Aspect ratio#
Adjust the Axes for a specified data aspect ratio.
Set the aspect ratio of the axes scaling, i.e. y/x-scale.
Return the aspect ratio of the axes scaling.
Set the Axes box aspect, i.e. the ratio of height to width.
Return the Axes box aspect, i.e. the ratio of height to width.
Set how the Axes adjusts to achieve the required aspect ratio.
Return whether the Axes will adjust its physical dimension (‘box’) or its data limits (‘datalim’) to achieve the desired aspect ratio.
Ticks and tick labels#
Set the xaxis’ tick locations and optionally labels.
Return the xaxis’ tick locations in data coordinates.
[Discouraged] Set the xaxis’ tick labels with list of string labels.Get the xaxis’ tick labels.
Return the xaxis’ major tick labels, as a list of Text .
Return the xaxis’ minor tick labels, as a list of Text .
Return the xaxis’ grid lines as a list of Line2D s.
Return the xaxis’ tick lines as a list of Line2D s.
Set up axis ticks and labels to treat data along the xaxis as dates.
Set the yaxis’ tick locations and optionally labels.
Return the yaxis’ tick locations in data coordinates.
[Discouraged] Set the yaxis’ tick labels with list of string labels.Get the yaxis’ tick labels.
Return the yaxis’ major tick labels, as a list of Text .
Return the yaxis’ minor tick labels, as a list of Text .
Return the yaxis’ grid lines as a list of Line2D s.
Return the yaxis’ tick lines as a list of Line2D s.
Set up axis ticks and labels to treat data along the yaxis as dates.
Remove minor ticks from the Axes.
Display minor ticks on the Axes.
Configure the ScalarFormatter used by default for linear Axes.
Change the appearance of ticks, tick labels, and gridlines.
Control behavior of major tick locators.
Units#
Convert x using the unit type of the xaxis.
Convert y using the unit type of the yaxis.
Return whether units are set on any axis.
Adding artists#
Add an Artist to the Axes; return the artist.
Add an AxesBase to the Axes’ children; return the child Axes.
Add a Collection to the Axes; return the collection.
Add a Container to the Axes’ containers; return the container.
Add an AxesImage to the Axes; return the image.
Add a Line2D to the Axes; return the line.
Add a Patch to the Axes; return the patch.
Add a Table to the Axes; return the table.
Twinning and sharing#
Create a twin Axes sharing the xaxis.
Create a twin Axes sharing the yaxis.
Share the x-axis with other.
Share the y-axis with other.
Return an immutable view on the shared x-axes Grouper.
Return an immutable view on the shared y-axes Grouper.
Axes position#
Define the anchor location.
Return the SubplotSpec associated with the subplot, or None.
Reset the active position to the original position.
Return the position of the Axes within the figure as a Bbox .
Async/event based#
Whether the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.
Call all of the registered callbacks.
Add a callback function that will be called whenever one of the Artist ‘s properties changes.
Remove a callback based on its observer id.
Interactive#
Return whether this Axes supports any pan/zoom button functionality.
Return whether this Axes supports the zoom box button functionality.
Get whether the Axes responds to navigation commands.
Set whether the Axes responds to navigation toolbar commands.
Get the navigation toolbar button status: ‘PAN’, ‘ZOOM’, or None.
Set the navigation toolbar button status.
Called when a pan operation has started.
Called when the mouse moves during a pan operation.
Called when a pan operation completes (when the mouse button is up.)
Return a format string formatting the x, y coordinates.
Return a string representation of data.
Return x formatted as an x-value.
Return y formatted as a y-value.
Return whether this artist is queried for custom context information when the mouse cursor moves over it.
Return whether the given event (in display coords) is in the Axes.
Test whether the artist contains the mouse event.
Return whether point (pair of pixel coordinates) is inside the Axes patch.
Return the cursor data for a given event.
Children#
Return a list of the child Artist s of this Artist .
Return a list of AxesImage s contained by the Axes.
Return a list of lines contained by the Axes.
Drawing#
Draw the Artist (and its children) using the given renderer.
Efficiently redraw a single artist.
Efficiently redraw Axes data, but not axis ticks, labels, etc.
Return the zorder value below which artists will be rasterized.
Set the zorder threshold for rasterization for vector graphics output.
Return the Axes bounding box in display space; args and kwargs are empty.
Return the tight bounding box of the Axes, including axis and their decorators (xlabel, title, etc).
Projection#
Methods used by Axis that must be overridden for non-rectilinear Axes.
Get the transformation used for drawing x-axis labels, ticks and gridlines.
Get the transformation used for drawing y-axis labels, ticks and gridlines.
Return the aspect ratio of the scaled data.
Other#
Return a default list of artists that are used for the bounding box calculation.
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
Return whether any artists have been added to the Axes.
Set multiple properties at once.
A sublist of Axes children based on their type.
The type-specific children sublists were made immutable in Matplotlib 3.7. In the future these artist lists may be replaced by tuples. Use as if this is a tuple already.
Parameters : axes Axes
The Axes from which this sublist will pull the children Artists.
prop_name str
The property name used to access this sublist from the Axes; used to generate deprecation warnings.
valid_types list of type, optional
A list of types that determine which children will be returned by this sublist. If specified, then the Artists in the sublist must be instances of any of these types. If unspecified, then any type of Artist is valid (unless limited by invalid_types.)
invalid_types tuple, optional
A list of types that determine which children will not be returned by this sublist. If specified, then Artists in the sublist will never be an instance of these types. Otherwise, no types will be excluded.
© Copyright 2002–2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012–2023 The Matplotlib development team.
Built from v3.7.2-2-g4915f574b8.