0% found this document useful (0 votes)
7 views36 pages

matplotlib Cheat Sheet

The document outlines a structured cheat sheet for Matplotlib, covering essential methods from the pyplot, Figure, and Axes objects, along with advanced concepts and exploration guidance. It emphasizes the core principles of using Matplotlib, including the state-based interface of pyplot and the object-oriented approach for detailed control. The cheat sheet includes examples of core plotting functions, customization options, and figure management techniques to provide a comprehensive understanding of the library's capabilities.

Uploaded by

Bharat Konduru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views36 pages

matplotlib Cheat Sheet

The document outlines a structured cheat sheet for Matplotlib, covering essential methods from the pyplot, Figure, and Axes objects, along with advanced concepts and exploration guidance. It emphasizes the core principles of using Matplotlib, including the state-based interface of pyplot and the object-oriented approach for detailed control. The cheat sheet includes examples of core plotting functions, customization options, and figure management techniques to provide a comprehensive understanding of the library's capabilities.

Uploaded by

Bharat Konduru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

I‭ understand you're looking for an‬‭exhaustive‬‭list‬‭of‬‭all‬‭methods related to Matplotlib, from‬

‭basic to advanced, with examples. This is a massive undertaking, as Matplotlib is an incredibly‬


‭vast library with hundreds of methods spread across various classes (Figure, Axes, Artist,‬
‭pyplot, etc.).‬

‭ isting‬‭every single method‬‭with an example for each‬‭would result in a document thousands‬


L
‭of lines long, likely exceeding the practical limits of a single response. It would also be highly‬
‭redundant as many methods have similar functionalities or are highly specialized.‬

‭ owever, I can provide you with a‬‭structured and significantly‬‭expanded cheat sheet‬‭that‬
H
‭aims to cover:‬
‭1.‬ T ‭ he most commonly used and important methods‬‭from‬‭pyplot, Figure, and Axes‬
‭objects.‬
‭2.‬ ‭More detailed explanations and examples‬‭for advanced‬‭concepts.‬
‭3.‬ ‭A guide on how to explore‬‭the library further to find‬‭specific methods you might need.‬

‭ his will give you a very strong foundation and cover almost all practical use cases, while also‬
T
‭teaching you how to delve deeper into the library's capabilities.‬

‭ he Comprehensive Matplotlib Cheat Sheet (Basic to‬


T
‭Advanced)‬
‭ atplotlib is vast, but its core revolves around Figure and Axes objects. We'll explore methods‬
M
‭associated with these, along with the convenience functions in pyplot.‬

‭Core Principle:‬
‭●‬ m ‭ atplotlib.pyplot (aliased as plt): Provides a state-based interface for quick and simple‬
‭plotting. It manages the current figure and axes for you.‬
‭●‬ ‭Object-Oriented (OO) Interface:‬‭Directly manipulates‬‭Figure objects (fig) and Axes‬
‭objects (ax). This is the recommended approach for complex or production-quality plots,‬
‭as it offers granular control.‬

‭Import Convention:‬

‭Python‬

‭import‬‭matplotlib.pyplot‬‭as‬‭plt‬
‭import‬‭numpy‬‭as‬‭np‬‭# Essential for data generation‬
‭Part 1: matplotlib.pyplot (plt) - The Quick and Easy Interface‬
‭ his module provides functions that implicitly create figures and axes and manage the current‬
T
‭state. Great for rapid prototyping.‬

‭I. Core Plotting Functions‬

‭Method‬ ‭Description‬ ‭Examples‬

‭plt.plot(x, y, ...)‬ ‭ ine Plot:‬‭Plots lines and/or‬


L ‭ lt.plot([1, 2, 3], [4, 5, 1],‬
p
‭markers. The workhorse for‬ ‭label='Series 1') <br>‬
‭2D plotting. Accepts‬ ‭plt.plot(x, y, 'r--o',‬
‭various keyword arguments‬ ‭label='Red Dashed Circles')‬
‭for customization.‬ ‭<br> plt.plot(x, y1, 'b-', x, y2,‬
‭'g:')‬

‭plt.scatter(x, y, ...)‬ ‭ catter Plot:‬‭Creates a‬


S ‭ lt.scatter(data_x, data_y,‬
p
‭scatter plot of x vs y.‬ ‭s=100, c='red', alpha=0.5)‬
‭Markers can be sized (s),‬ ‭<br> plt.scatter(x, y,‬
‭colored (c), and have‬ ‭s=sizes, c=colors,‬
‭transparency (alpha).‬ ‭cmap='viridis')‬

‭plt.bar(x, height, ...)‬ ‭ ertical Bar Chart:‬‭Plots‬


V ‭ lt.bar(['A', 'B'], [10, 20],‬
p
‭bars with x categories and‬ ‭color='skyblue') <br>‬
‭height values.‬ ‭plt.bar(index, values,‬
‭width=0.8)‬

‭plt.barh(y, width, ...)‬ ‭ orizontal Bar Chart:‬


H ‭ lt.barh(['X', 'Y'], [5, 15],‬
p
‭Plots horizontal bars.‬ ‭color='lightgreen')‬

‭plt.hist(x, bins=..., ...)‬ ‭ istogram:‬‭Plots the‬


H ‭ lt.hist(np.random.randn(1‬
p
‭distribution of x. bins‬ ‭000), bins=20,‬
‭controls the number/edges‬ ‭edgecolor='black')‬
‭of bins.‬

‭plt.boxplot(x, ...)‬ ‭ ox Plot:‬‭Displays the‬


B ‭ lt.boxplot([data1, data2],‬
p
‭distribution of data based‬ ‭labels=['Group 1', 'Group‬
‭on quartiles.‬ ‭2'])‬
‭plt.pie(x, labels=..., ...)‬ ‭ ie Chart:‬‭Creates a‬
P ‭ lt.pie([15, 30, 45],‬
p
‭circular chart divided into‬ ‭labels=['Slice A', 'Slice B',‬
‭slices representing‬ ‭'Slice C'],‬
‭proportions.‬ ‭autopct='%1.1f%%')‬

‭plt.imshow(X, ...)‬ I‭ mage Display:‬‭Displays‬ i‭mg_data =‬


‭data as an image (e.g., 2D‬ ‭np.random.rand(10, 10)‬
‭NumPy array). Often used‬ ‭<br> plt.imshow(img_data,‬
‭for heatmaps or actual‬ ‭cmap='hot', origin='lower')‬
‭image data.‬

‭plt.pcolor(X, Y, Z, ...)‬ ‭ seudocolor Plot‬


P ‭ lt.pcolor(X_grid, Y_grid,‬
p
‭(Rectangular Grid):‬ ‭Z_values, cmap='RdBu_r')‬
‭Creates a pseudocolor plot‬
‭of a 2D array. More flexible‬
‭than imshow for‬
‭non-uniform grids.‬

‭plt.contour(X, Y, Z, ...)‬ ‭ ontour Plot:‬‭Draws‬


C ‭ lt.contour(X_grid, Y_grid,‬
p
‭contour lines for data on a‬ ‭Z_values, levels=10,‬
‭grid.‬ ‭colors='black')‬

‭plt.contourf(X, Y, Z, ...)‬ ‭ illed Contour Plot:‬‭Draws‬


F ‭ lt.contourf(X_grid, Y_grid,‬
p
‭filled contours.‬ ‭Z_values, levels=10,‬
‭cmap='viridis')‬

‭ lt.errorbar(x, y, yerr=...,‬
p ‭ rror Bar Plot:‬‭Plots x, y‬
E ‭ lt.errorbar(x_data, y_data,‬
p
‭xerr=..., ...)‬ ‭with error bars.‬ ‭yerr=y_errors, fmt='-o')‬

‭II. Plot Customization Functions‬

‭Method‬ ‭Description‬ ‭Examples‬

‭plt.title(title_str, ...)‬ ‭ ets the title of the current‬


S ‭ lt.title("My Awesome Plot",‬
p
‭plot.‬ ‭fontsize=16,‬
‭color='darkblue')‬

‭plt.xlabel(label_str, ...)‬ ‭ ets the label for the‬


S ‭ lt.xlabel("Time (s)",‬
p
‭x-axis.‬ ‭labelpad=10)‬
‭plt.ylabel(label_str, ...)‬ ‭ ets the label for the‬
S ‭ lt.ylabel("Amplitude",‬
p
‭y-axis.‬ ‭fontsize=12)‬

‭plt.legend(labels=..., ...)‬ ‭ isplays a legend. Requires‬


D ‭ lt.legend(loc='upper right',‬
p
‭label argument in plotting‬ ‭shadow=True,‬
‭functions.‬ ‭fancybox=True)‬

‭plt.xlim(xmin, xmax)‬ ‭ ets or gets the x-axis‬


S ‭plt.xlim(0, 10)‬
‭limits.‬

‭plt.ylim(ymin, ymax)‬ ‭ ets or gets the y-axis‬


S ‭plt.ylim(-1.5, 1.5)‬
‭limits.‬

‭plt.xticks(ticks, labels, ...)‬ ‭ ets or gets the x-axis tick‬


S ‭ lt.xticks([0, 1, 2], ['Zero',‬
p
‭locations and labels.‬ ‭'One', 'Two'], rotation=45)‬

‭plt.yticks(ticks, labels, ...)‬ ‭ ets or gets the y-axis tick‬


S ‭ lt.yticks(np.arange(-1, 1.1,‬
p
‭locations and labels.‬ ‭0.5))‬

‭plt.grid(b=True, ...)‬ ‭Configures the grid lines.‬ ‭ lt.grid(True, linestyle='--',‬


p
‭alpha=0.6, color='gray')‬

‭plt.text(x, y, s, ...)‬ ‭ dds text to the plot at‬


A ‭ lt.text(5, 0.8, 'Peak Value',‬
p
‭coordinates (x, y).‬ ‭fontsize=10, color='red')‬

‭ lt.annotate(s, xy, xytext,‬


p ‭ dds an annotation with an‬
A ‭ lt.annotate('Local Max',‬
p
‭...)‬ ‭arrow.‬ ‭xy=(np.pi/2, 1), xytext=(2,‬
‭0.5),‬
‭arrowprops=dict(facecolor‬
‭='black', shrink=0.05))‬

‭plt.figtext(x, y, s, ...)‬ ‭ dds text to the figure‬


A ‭ lt.figtext(0.5, 0.95, 'Overall‬
p
‭(normalized coordinates).‬ ‭Figure Title', ha='center',‬
‭fontsize=18)‬

‭plt.axis('equal')‬ ‭ ets equal scaling (e.g., for‬


S ‭plt.axis('equal')‬
‭circles in scatter plots).‬

‭plt.autoscale(enable=True,‬ ‭Autoscale axis limits.‬ ‭plt.autoscale(enable=True,‬


‭axis='both', tight=None)‬ ‭axis='x', tight=True)‬

‭plt.tick_params(axis='x', ...)‬ ‭Configures tick properties.‬ ‭ lt.tick_params(axis='x',‬


p
‭direction='in', length=6,‬
‭colors='r')‬

‭III. Figure Management & Layout‬

‭Method‬ ‭Description‬ ‭Examples‬

‭ lt.figure(figsize=(w, h),‬
p ‭ reates a new figure.‬
C ‭ lt.figure(figsize=(8, 6),‬
p
‭dpi=..., ...)‬ ‭figsize is in inches.‬ ‭dpi=100,‬
‭facecolor='lightgray')‬

‭ lt.subplot(nrows, ncols,‬
p ‭ reates a single subplot‬
C ‭ lt.subplot(2, 1, 1) (top plot‬
p
‭index, ...)‬ ‭within a grid.‬ ‭of 2)‬

‭ lt.subplots(nrows=1,‬
p ‭ ecommended:‬‭Creates a‬
R ‭ g, ax = plt.subplots() <br>‬
fi
‭ncols=1, ...)‬ ‭figure and a grid of‬ ‭fig, axs = plt.subplots(2, 2)‬
‭subplots (returns fig, axes).‬

‭plt.tight_layout()‬ ‭ utomatically adjusts‬


A ‭plt.tight_layout()‬
‭subplot parameters for a‬
‭tight layout.‬

‭plt.show()‬ ‭ isplays the current‬


D ‭plt.show()‬
‭figure(s). This call blocks‬
‭execution until the plot‬
‭window is closed.‬

‭ lt.savefig(fname, dpi=...,‬
p ‭ aves the current figure to‬
S ‭ lt.savefig('my_plot.pdf',‬
p
‭...)‬ ‭a file.‬ ‭dpi=300,‬
‭bbox_inches='tight')‬

‭plt.clf()‬ ‭Clears the current figure.‬ ‭plt.clf()‬

‭plt.cla()‬ ‭Clears the current axes.‬ ‭plt.cla()‬


‭plt.close(fig_or_all)‬ ‭ loses a specific figure or‬
C ‭ lt.close() (current) <br>‬
p
‭all figures.‬ ‭plt.close('all')‬

‭Full Example (Pyplot Interface):‬

‭Python‬

‭import‬‭matplotlib.pyplot‬‭as‬‭plt‬
‭import‬‭numpy‬‭as‬‭np‬

‭# Data‬
x‭ = np.linspace(‬‭0‭,‬‬‭2‬‭* np.pi,‬‭400‬‭)‬
‭y_sin = np.sin(x)‬
‭y_cos = np.cos(x)‬
‭y_random = np.random.rand(‬‭400‬‭) *‬‭0.5‬‭-‬‭0.25‬‭# Small‬‭noise‬

‭plt.figure(figsize=(‬‭10‬‭,‬‭6‬‭))‬‭# Create a figure with‬‭custom size‬

‭# Plot Sine wave‬


‭plt.plot(x, y_sin, color=‬‭'blue'‬‭, linestyle=‬‭'-'‬‭, linewidth=‬‭2‬‭,‬‭label=‬‭'Sine Wave'‬‭)‬

‭# Plot Cosine wave‬


‭plt.plot(x, y_cos, color=‬‭'red'‬‭, linestyle=‬‭'--'‬‭, linewidth=‬‭1.5‬‭,‬‭label=‬‭'Cosine Wave'‬‭)‬

‭# Add scatter plot (e.g., some measurements with errors)‬


‭plt.errorbar(x[::‬‭40‬‭], y_sin[::‬‭40‬‭] + y_random[::‬‭40‬‭],‬‭yerr=‬‭0.1‬‭, fmt=‬‭'o'‬‭, color=‬‭'green'‬‭, markersize=‬‭6‬‭,‬
‭label=‬‭'Measurements'‬‭)‬

‭# Customize plot‬
‭plt.title(‬‭"Trigonometric Functions with Random Measurements"‬‭,‬‭fontsize=‬‭18‬‭, fontweight=‬‭'bold'‬‭)‬
‭ lt.xlabel(‬‭"Angle (radians)"‬‭, fontsize=‬‭14‬‭)‬
p
‭plt.ylabel(‬‭"Amplitude"‬‭, fontsize=‬‭14‬‭)‬
‭plt.grid(‬‭True‬‭, linestyle=‬‭':'‬‭, alpha=‬‭0.7‬‭)‬
‭plt.legend(loc=‬‭'upper right'‬‭, shadow=‬‭True‬‭, fontsize=‬‭12‬‭)‬
‭plt.xlim(‬‭0‭,‬‬‭2‬‭* np.pi)‬
‭plt.ylim(-‬‭1.5‬‭,‬‭1.5‬‭)‬

‭# Add a text annotation‬


‭plt.text(np.pi,‬‭1.2‬‭,‬‭'Key Features'‬‭, horizontalalignment=‬‭'center'‬‭,‬
‭bbox=‬‭dict‬‭(facecolor=‬‭'white'‬‭, alpha=‬‭0.7‬‭, edgecolor=‬‭'none'‬‭))‬

‭# Save and Show‬


‭plt.savefig(‬‭'pyplot_example.png'‬‭, dpi=‬‭300‬‭, bbox_inches=‬‭'tight'‬‭)‬
‭plt.show()‬

‭Part 2: Object-Oriented (OO) Interface - Figure and Axes Objects‬


‭ his is the preferred way for more complex or production-ready plots, as it gives you explicit‬
T
‭control over every element.‬

‭Python‬

‭fig, ax = plt.subplots()‬‭# Common way to get a figure‬‭and axes‬

‭I. Figure Object Methods (fig)‬


‭The Figure object is the top-level container for all the plot elements.‬

‭Method‬ ‭Description‬ ‭Examples‬

‭fig.add_subplot(...)‬ ‭ dds an Axes to the figure,‬


A ‭ x1 = fig.add_subplot(2, 1,‬
a
‭similar to plt.subplot().‬ ‭1)‬

‭ g.add_axes([left, bottom,‬
fi ‭ dds an Axes at an‬
A ‭ x_inset =‬
a
‭width, height])‬ ‭arbitrary position‬ ‭fig.add_axes([0.6, 0.6,‬
‭(normalized coordinates‬ ‭0.25, 0.25])‬
‭from 0 to 1).‬

‭fig.suptitle(title, ...)‬ ‭ dds a super title to the‬


A ‭ g.suptitle('Overall‬
fi
‭figure (above all subplots).‬ ‭Experiment Results',‬
‭fontsize=20)‬

‭ g.colorbar(mappable,‬
fi ‭ reates a colorbar.‬
C ‭ bar = fig.colorbar(im,‬
c
‭ax=..., ...)‬ ‭mappable is often returned‬ ‭ax=ax, label='Intensity')‬
‭by functions like imshow,‬
‭scatter.‬
‭fig.set_size_inches(w, h)‬ ‭ ets the figure size in‬
S ‭fig.set_size_inches(12, 7)‬
‭inches.‬

‭fig.savefig(fname, ...)‬ ‭ aves the figure. Same‬


S ‭ g.savefig('my_figure.png',‬
fi
‭args as plt.savefig().‬ ‭dpi=300)‬

‭fig.canvas.draw()‬ ‭ edraws the figure. Useful‬


R ‭fig.canvas.draw()‬
‭for interactive updates.‬

‭fig.clf()‬ ‭ lears the entire figure,‬


C ‭fig.clf()‬
‭removing all subplots.‬

‭II. Axes Object Methods (ax)‬


‭ he Axes object is where the actual data is plotted. Most plotting and customization happens‬
T
‭here.‬

‭A. Plotting Methods (Prefix ax.)‬


‭ hese are the OO equivalents of plt. functions. They return Artist objects (lines, patches, etc.)‬
T
‭that can be further customized.‬

‭Method‬ ‭Description‬ ‭Examples‬

‭ax.plot(x, y, ...)‬ ‭Line plot on this axes.‬ ‭ x.plot(x, y, 'b-', label='Data‬


a
‭1')‬

‭ax.scatter(x, y, ...)‬ ‭Scatter plot on this axes.‬ ‭ x.scatter(x, y, s=50,‬


a
‭c='red')‬

‭ax.bar(x, height, ...)‬ ‭ ertical bar chart on this‬


V ‭ax.bar(categories, values)‬
‭axes.‬

‭ax.hist(x, ...)‬ ‭Histogram on this axes.‬ ‭ax.hist(data, bins=20)‬

‭ax.boxplot(x, ...)‬ ‭Box plot on this axes.‬ ‭ax.boxplot(data)‬

‭ax.pie(x, ...)‬ ‭Pie chart on this axes.‬ ‭ax.pie(sizes)‬


‭ax.imshow(X, ...)‬ ‭Image display on this axes.‬ ‭ax.imshow(img_data)‬

‭ax.pcolor(X, Y, Z, ...)‬ ‭ seudocolor plot on this‬


P ‭ x.pcolor(X_grid, Y_grid,‬
a
‭axes.‬ ‭Z_values)‬

‭ax.contour(X, Y, Z, ...)‬ ‭Contour plot on this axes.‬ ‭ x.contour(X_grid, Y_grid,‬


a
‭Z_values)‬

‭ax.contourf(X, Y, Z, ...)‬ ‭ illed contour plot on this‬


F ‭ x.contourf(X_grid, Y_grid,‬
a
‭axes.‬ ‭Z_values)‬

‭ax.errorbar(x, y, ...)‬ ‭Error bar plot on this axes.‬ ‭ x.errorbar(x_data, y_data,‬


a
‭yerr=errors)‬

‭ax.fill_between(x, y1, y2, ...)‬ ‭ ills the area between two‬


F ‭ x.fill_between(x, y_lower,‬
a
‭curves.‬ ‭y_upper, alpha=0.3)‬

‭ax.fill(x, y, ...)‬ ‭Fills a polygon.‬ ‭ x.fill([0,1,1,0], [0,0,1,1],‬


a
‭color='cyan')‬

‭ax.stem(x, y, ...)‬ ‭ reates a stem plot (useful‬


C ‭ x.stem(indices,‬
a
‭for discrete signals).‬ ‭amplitudes)‬

‭ax.vlines(x, ymin, ymax, ...)‬ ‭Vertical lines.‬ ‭ x.vlines([2, 5], 0, 10,‬


a
‭colors='grey',‬
‭linestyles='--')‬

‭ax.hlines(y, xmin, xmax, ...)‬ ‭Horizontal lines.‬ ‭ x.hlines([5, 8], 0, 10,‬


a
‭colors='red', linestyles=':')‬

‭B. Customization Methods (Prefix ax.set_)‬


‭These are the OO equivalents for setting titles, labels, limits, etc.‬

‭Method‬ ‭Description‬ ‭Examples‬

‭ax.set_title(title_str, ...)‬ ‭Sets the title for‬‭this‬‭axes.‬ ‭ x.set_title("My Subplot‬


a
‭Title")‬
‭ax.set_xlabel(label_str, ...)‬ ‭ ets the x-axis label for‬‭this‬
S ‭ax.set_xlabel("Time (s)")‬
‭axes.‬

‭ax.set_ylabel(label_str, ...)‬ ‭ ets the y-axis label for‬‭this‬


S ‭ax.set_ylabel("Value")‬
‭axes.‬

‭ax.set_xlim(xmin, xmax)‬ ‭ ets the x-axis limits for‬


S ‭ax.set_xlim(0, 10)‬
‭this‬‭axes.‬

‭ax.set_ylim(ymin, ymax)‬ ‭ ets the y-axis limits for‬


S ‭ax.set_ylim(-1, 1)‬
‭this‬‭axes.‬

‭ax.set_xticks(ticks)‬ ‭ ets the x-axis tick‬


S ‭ x.set_xticks(np.arange(0,‬
a
‭locations.‬ ‭10, 2))‬

‭ x.set_xticklabels(labels,‬
a ‭Sets the x-axis tick labels.‬ ‭ x.set_xticklabels(['Mon',‬
a
‭...)‬ ‭'Tue', 'Wed'])‬

‭ax.set_yticks(ticks)‬ ‭ ets the y-axis tick‬


S ‭ax.set_yticks([-1, 0, 1])‬
‭locations.‬

‭ax.set_yticklabels(labels, ...)‬ ‭Sets the y-axis tick labels.‬ ‭ x.set_yticklabels(['Low',‬


a
‭'Mid', 'High'])‬

‭ax.set_xscale(value)‬ ‭ ets the x-axis scale‬


S ‭ax.set_xscale('log')‬
‭('linear', 'log', 'symlog',‬
‭'logit').‬

‭ax.set_yscale(value)‬ ‭Sets the y-axis scale.‬ ‭ax.set_yscale('log')‬

‭ax.set_aspect(value)‬ ‭ ets the aspect ratio of the‬


S ‭ax.set_aspect('equal')‬
‭plot.‬

‭ax.set_facecolor(color)‬ ‭ ets the background color‬


S ‭ x.set_facecolor('lightgray'‬
a
‭of the axes.‬ ‭)‬

‭C. Other Customization Methods (Prefix ax.)‬


‭Method‬ ‭Description‬ ‭Examples‬

‭ax.legend(loc=..., ...)‬ ‭ isplays a legend for‬‭this‬


D ‭ x.legend(loc='lower left',‬
a
‭axes.‬ ‭frameon=False)‬

‭ax.grid(b=True, ...)‬ ‭ onfigures grid lines for‬


C ‭ x.grid(True, axis='y',‬
a
‭this‬‭axes.‬ ‭linestyle='--', alpha=0.5)‬

‭ax.text(x, y, s, ...)‬ ‭Adds text to‬‭this‬‭axes.‬ ‭ x.text(0.5, 0.5, 'Center‬


a
‭Text',‬
‭transform=ax.transAxes)‬
‭(normalized to axes)‬

‭ax.annotate(s, xy, ...)‬ ‭ dds an annotation with an‬


A ‭ x.annotate('Point of‬
a
‭arrow for‬‭this‬‭axes.‬ ‭interest', xy=(x_val, y_val),‬
‭...)‬

‭ax.tick_params(axis='x', ...)‬ ‭ onfigures tick properties‬


C ‭ x.tick_params(axis='both',‬
a
‭for‬‭this‬‭axes.‬ ‭which='major',‬
‭labelsize=10)‬

‭ax.invert_xaxis()‬ ‭Inverts the x-axis.‬ ‭ax.invert_xaxis()‬

‭ax.invert_yaxis()‬ ‭Inverts the y-axis.‬ ‭ax.invert_yaxis()‬

‭ x.spines[position].set_visi‬
a ‭ ontrols visibility of plot‬
C ‭ x.spines['right'].set_visible‬
a
‭ble(bool)‬ ‭borders.‬ ‭(False)‬

‭ x.spines[position].set_col‬
a ‭Sets color of plot borders.‬ ‭ x.spines['left'].set_color('b‬
a
‭or(color)‬ ‭lue')‬

‭ x.tick_params(which='bot‬
a ‭Control tick mark direction.‬ ‭ x.tick_params(which='maj‬
a
‭h', direction='inout')‬ ‭or', length=7, width=2)‬

‭ax.set_title(..., pad=...)‬ ‭Adjusts title padding.‬ ‭ax.set_title('Title', pad=20)‬

‭ax.axvline(x, ...)‬ ‭ raws a vertical line across‬


D ‭ x.axvline(x=5, color='gray',‬
a
‭the axes.‬ ‭linestyle='--')‬
‭ax.axhline(y, ...)‬ ‭ raws a horizontal line‬
D ‭ x.axhline(y=0.5,‬
a
‭across the axes.‬ ‭color='gray', linestyle=':')‬

‭ax.axvspan(xmin, xmax, ...)‬ ‭ raws a vertical shaded‬


D ‭ x.axvspan(1, 3,‬
a
‭region.‬ ‭color='yellow', alpha=0.3)‬

‭ax.axhspan(ymin, ymax, ...)‬ ‭ raws a horizontal shaded‬


D ‭ x.axhspan(0.2, 0.8,‬
a
‭region.‬ ‭color='cyan', alpha=0.3)‬

‭ x.set_aspect('auto'/'equal'‬
a ‭Sets the aspect ratio.‬ ‭ x.set_aspect('equal',‬
a
‭/'num')‬ ‭adjustable='box')‬

‭ax.format_xdata(formatter)‬ ‭ et the formatter for x-axis‬


S ‭ x.format_xdata =‬
a
‭data (for interactive‬ ‭plt.FuncFormatter(my_x_for‬
‭tooltips).‬ ‭matter)‬

‭Full Example (Object-Oriented Interface with Subplots):‬

‭Python‬

‭import‬‭matplotlib.pyplot‬‭as‬‭plt‬
‭import‬‭numpy‬‭as‬‭np‬

‭# Data‬
x‭ _common = np.linspace(‬‭0‬‭,‬‭10‬‭,‬‭100‬‭)‬
‭y1 = np.sin(x_common)‬
‭y2 = np.cos(x_common) *‬‭0.5‬
‭y3 = x_common + np.random.randn(‬‭100‬‭) *‬‭2‬
‭y4_hist = np.random.normal(‬‭0‭,‬‬‭1‬‭,‬‭1000‬‭)‬
‭y5_scatter_x = np.random.rand(‬‭50‬‭) *‬‭10‬
‭y5_scatter_y = np.random.rand(‬‭50‬‭) *‬‭5‬
‭y5_scatter_c = np.random.rand(‬‭50‬‭)‬

‭# Create a figure and a 2x2 grid of subplots‬


‭fig, axs = plt.subplots(‬‭2‭,‬‬‭2‭,‬ figsize=(‬‭12‬‭,‬‭9‬‭), layout=‬‭'constrained'‬‭)‬‭# 'constrained_layout' for tight‬
‭layout‬

‭# --- Plot 1: Top-Left (Line Plot with Customizations) ---‬


‭ xs[‬‭0‬‭,‬‭0‭]‬ .plot(x_common, y1, label=‬‭'Sine'‬‭, color=‬‭'darkblue'‬‭, linewidth=‬‭2‬‭)‬
a
‭axs[‬‭0‬‭,‬‭0‭]‬ .plot(x_common, y2, label=‬‭'Cosine (scaled)'‬‭,‬‭color=‬‭'green'‬‭, linestyle=‬‭':'‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .set_title(‬‭'Waveforms'‬‭, fontsize=‬‭14‬‭, pad=‬‭10‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .set_xlabel(‬‭'Time (units)'‬‭, fontsize=‬‭12‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .set_ylabel(‬‭'Amplitude'‬‭, fontsize=‬‭12‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .legend(frameon=‬‭True‬‭, shadow=‬‭True‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .grid(‬‭True‬‭, linestyle=‬‭'--'‬‭, alpha=‬‭0.6‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .set_ylim(-‬‭1.2‬‭,‬‭1.2‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .tick_params(axis=‬‭'both'‬‭, which=‬‭'major'‬‭,‬‭labelsize=‬‭10‬‭, direction=‬‭'inout'‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .spines[‬‭'right'‬‭].set_visible(‬‭False‬‭)‬
‭axs[‬‭0‬‭,‬‭0‭]‬ .spines[‬‭'top'‬‭].set_visible(‬‭False‬‭)‬

‭# --- Plot 2: Top-Right (Scatter Plot with Colorbar & TwinX) ---‬
‭scatter = axs[‬‭0‭,‬‬‭1‭]‬ .scatter(y5_scatter_x, y5_scatter_y,‬‭c=y5_scatter_c, cmap=‬‭'viridis'‬‭, s=‬‭80‬‭,‬
‭ lpha=‬‭0.8‬‭, edgecolor=‬‭'k'‬‭)‬
a
‭axs[‬‭0‬‭,‬‭1‭]‬ .set_title(‬‭'Data Points with Intensity'‬‭,‬‭fontsize=‬‭14‬‭)‬
‭axs[‬‭0‬‭,‬‭1‭]‬ .set_xlabel(‬‭'Feature 1'‬‭)‬
‭axs[‬‭0‬‭,‬‭1‭]‬ .set_ylabel(‬‭'Feature 2'‬‭)‬
‭fig.colorbar(scatter, ax=axs[‬‭0‭,‬‬‭1‬‭], label=‬‭'Intensity‬‭Scale'‬‭, shrink=‬‭0.7‬‭)‬

‭# Add a second y-axis (twinx)‬


‭ax_twin = axs[‬‭0‭,‬‬‭1‭]‬ .twinx()‬
‭ x_twin.plot(y5_scatter_x, y5_scatter_x *‬‭0.1‬‭+‬‭0.5‬‭,‬‭color=‬‭'orange'‬‭, linestyle=‬‭'-'‬‭, label=‬‭'Trend'‬‭)‬
a
‭ax_twin.set_ylabel(‬‭'Auxiliary Metric'‬‭, color=‬‭'orange'‬‭)‬
‭ax_twin.tick_params(axis=‬‭'y'‬‭, labelcolor=‬‭'orange'‬‭)‬
‭ax_twin.legend(loc=‬‭'upper left'‬‭)‬

‭# --- Plot 3: Bottom-Left (Histogram with Annotation) ---‬


‭n, bins, patches = axs[‬‭1‭,‬‬‭0‭]‬ .hist(y4_hist, bins=‬‭30‬‭,‬‭color=‬‭'purple'‬‭, edgecolor=‬‭'black'‬‭, alpha=‬‭0.7‬‭,‬
‭ ensity=‬‭True‬‭)‬
d
‭axs[‬‭1‬‭,‬‭0‭]‬ .set_title(‬‭'Distribution of Data'‬‭, fontsize=‬‭14‬‭)‬
‭axs[‬‭1‬‭,‬‭0‭]‬ .set_xlabel(‬‭'Value'‬‭)‬
‭axs[‬‭1‬‭,‬‭0‭]‬ .set_ylabel(‬‭'Density'‬‭)‬
‭axs[‬‭1‬‭,‬‭0‭]‬ .text(‬‭0.05‬‭,‬‭0.95‬‭,‬‭f'Mean:‬‭{np.mean(y4_hist):‬‭.2‬‭f}‬‭\nStd‬‭Dev:‬‭{np.std(y4_hist):‬‭.2‬‭f}‬‭'‭,‬‬
‭transform=axs[‬‭1‭,‬‬‭0‬‭].transAxes, fontsize=‬‭10‬‭,‬‭verticalalignment=‬‭'top'‬‭,‬
‭bbox=‬‭dict‬‭(boxstyle=‬‭'round,pad=0.5'‬‭,‬‭fc=‬‭'yellow'‬‭, alpha=‬‭0.5‬‭))‬

‭# --- Plot 4: Bottom-Right (Line Plot with Fill Between & Inset) ---‬
‭line, = axs[‬‭1‭,‬‬‭1‬‭].plot(x_common, y3, color=‬‭'teal'‬‭,‬‭label=‬‭'Noisy Data'‬‭)‬
‭axs[‬‭1‬‭,‬‭1‬‭].fill_between(x_common, y3 -‬‭2‭,‬ y3 +‬‭2‭,‬ color=‬‭'teal'‬‭,‬‭alpha=‬‭0.2‬‭, label=‬‭'Confidence‬
‭Interval'‬‭)‬
‭axs[‬‭1‬‭,‬‭1‬‭].set_title(‬‭'Noisy Data with CI'‬‭, fontsize=‬‭14‬‭)‬
‭axs[‬‭1‬‭,‬‭1‬‭].set_xlabel(‬‭'Index'‬‭)‬
‭ xs[‬‭1‬‭,‬‭1‬‭].set_ylabel(‬‭'Measurement'‬‭)‬
a
‭axs[‬‭1‬‭,‬‭1‬‭].legend()‬

‭# Add an inset plot‬


‭inset_ax = axs[‬‭1‭,‬‬‭1‬‭].inset_axes([‬‭0.6‬‭,‬‭0.1‬‭,‬‭0.38‬‭,‬‭0.38‬‭])‬‭# [x, y, width, height] in axes coordinates‬
i‭nset_ax.plot(x_common[‬‭0‭:‬‬‭10‬‭], y3[‬‭0‬‭:‭1‬ 0‬‭],‬‭'r-o'‬‭, markersize=‬‭4‬‭)‬
‭inset_ax.set_title(‬‭'Zoom In'‬‭, fontsize=‬‭8‬‭, pad=‬‭0‬‭)‬
‭inset_ax.set_xlim(‬‭0‭,‬‬‭2‭)‬ ‬
‭inset_ax.set_ylim(-‬‭5‭,‬‬‭5‬‭)‬
‭inset_ax.tick_params(labelsize=‬‭6‬‭)‬
‭inset_ax.set_facecolor(‬‭'lightyellow'‬‭)‬
‭inset_ax.grid(‬‭True‬‭, linestyle=‬‭':'‬‭, alpha=‬‭0.5‬‭)‬

‭# Overall Figure Title‬


‭fig.suptitle(‬‭"Comprehensive Matplotlib Example with‬‭Subplots"‬‭, fontsize=‬‭22‬‭, y=‬‭1.03‬‭)‬

‭ Adjust layout for better spacing (already handled by layout='constrained')‬


#
‭# plt.tight_layout()‬

‭plt.show()‬

‭Part 3: Advanced Topics & Concepts‬


1‭ . Colormaps (cmap)‬
‭Used to map numerical values to colors. Critical for heatmaps, scatter plots with color‬
‭dimension, etc.‬
‭●‬ ‭Sequential:‬‭viridis, plasma, inferno, magma, cividis,‬‭Greens, Blues‬
‭●‬ ‭Diverging:‬‭coolwarm, RdBu, bwr‬
‭●‬ ‭Qualitative:‬‭tab10, Paired (for categorical data,‬‭but typically used with plt.cm.get_cmap‬
‭and integer indices)‬

‭Usage:‬‭Pass cmap='colormap_name' to functions like‬‭imshow, scatter, pcolor, contourf.‬

‭ . Customizing Artist Objects‬


2
‭Most plt. and ax. plotting functions return Artist objects (e.g., Line2D, PathCollection,‬
‭Rectangle). You can customize them after creation.‬

‭Python‬

‭line, = ax.plot(x, y)‬‭# Notice the comma to unpack‬‭the list returned by plot‬
l‭ine.set_color(‬‭'red'‬‭)‬
‭line.set_linewidth(‬‭3‭)‬ ‬
‭line.set_linestyle(‬‭'--'‬‭)‬

‭# For scatter plots, the return is a PathCollection‬


‭scatter_plot = ax.scatter(x, y, s=‬‭50‬‭)‬
s‭ catter_plot.set_alpha(‬‭0.6‬‭)‬
‭scatter_plot.set_edgecolor(‬‭'blue'‬‭)‬

‭ . Text Properties & Math Text‬


3
‭Matplotlib supports LaTeX-like math text.‬

‭Python‬

‭ lt.title(‬‭r'$\alpha^2 + \beta^2 = \gamma^2$'‬‭, fontsize=‬‭16‬‭)‬‭# Use r'' for raw string‬


p
‭plt.xlabel(‬‭r'Time $\Delta t$ (s)'‬‭)‬
‭plt.text(‬‭0.5‬‭,‬‭0.5‬‭,‬‭r'$E=mc^2$'‬‭, fontsize=‬‭20‬‭, color=‬‭'red'‬‭)‬

‭ . Event Handling & Interactivity‬


4
‭Matplotlib allows you to respond to user interactions (clicks, key presses, mouse movements).‬

‭Python‬

‭def‬‭onclick‬‭(event):‬
‭print(‬‭f'Button‬‭{event.button}‬‭clicked at data‬‭coords: (‬‭{event.xdata:‬‭.2‬‭f}‬‭,‬‭{event.ydata:‬‭.2‬‭f}‬‭)'‬‭)‬

‭ g, ax = plt.subplots()‬
fi
‭ax.plot(np.random.rand(‬‭10‬‭))‬
‭fig.canvas.mpl_connect(‬‭'button_press_event'‬‭, onclick)‬‭# Connect event‬
‭plt.show()‬

‭‬
● '‭button_press_event'‬
‭●‬ ‭'motion_notify_event'‬
‭●‬ ‭'key_press_event'‬
‭●‬ ‭'scroll_event'‬

‭ . Customizing Ticks and Spines‬


5
‭Deep control over axis appearance.‬
‭Python‬

‭ax.tick_params(axis=‬‭'both'‬‭, which=‬‭'major'‬‭, direction=‬‭'in'‬‭,‬‭length=‬‭8‬‭, width=‬‭2‬‭, colors=‬‭'grey'‬‭,‬


‭grid_color=‬‭'r'‬‭, grid_alpha=‬‭0.5‬‭, labelbottom=‬‭True‬‭,‬‭labelleft=‬‭True‬‭)‬

‭ x.spines[‬‭'left'‬‭].set_position((‬‭'outward'‬‭,‬‭10‬‭))‬‭#‬‭Move spine outwards‬


a
‭ax.spines[‬‭'bottom'‬‭].set_linewidth(‬‭2‭)‬ ‬
‭ax.spines[‬‭'left'‬‭].set_bounds(-‬‭1‭,‬‬‭1‬‭)‬‭# Set limits for‬‭the visible part of the spine‬

‭ . Transforms‬
6
‭Understanding how data coordinates are transformed to display coordinates.‬
‭●‬ ‭ax.transData: Data coordinates.‬
‭●‬ ‭ax.transAxes: Axes coordinates (0,0 to 1,1 within the axes bounding box).‬
‭●‬ ‭fig.transFigure: Figure coordinates (0,0 to 1,1 within the figure bounding box).‬

‭Useful for placing text or annotations relative to the plot or figure.‬

‭ . Stylesheets (plt.style.use())‬
7
‭Quickly change the aesthetic of your plots.‬

‭Python‬

‭ List available styles‬


#
‭# print(plt.style.available)‬

‭ lt.style.use(‬‭'seaborn-v0_8-darkgrid'‬‭)‬‭# Or 'ggplot',‬‭'fivethirtyeight', 'dark_background'‬


p
‭fig, ax = plt.subplots()‬
‭ax.plot([‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ )‬
‭plt.show()‬
‭plt.style.use(‬‭'default'‬‭)‬‭# Reset‬

‭ . Animations (matplotlib.animation)‬
8
‭Create dynamic plots.‬

‭Python‬
‭from‬‭matplotlib.animation‬‭import‬‭FuncAnimation‬

‭ g, ax = plt.subplots()‬
fi
‭x_data, y_data = [], []‬
‭line, = ax.plot([], [],‬‭'r-'‬‭)‬

‭def‬‭init‬‭():‬
‭ x.set_xlim(‬‭0‬‭,‬‭2‭*‬ np.pi)‬
a
‭ax.set_ylim(-‬‭1.1‬‭,‬‭1.1‬‭)‬
‭return‬‭line,‬

‭def‬‭update‬‭(frame):‬
x‭ _data.append(frame)‬
‭y_data.append(np.sin(frame))‬
‭line.set_data(x_data, y_data)‬
‭return‬‭line‬‭,‬

‭ani = FuncAnimation(fig, update, frames=np.linspace(‬‭0‬‭,‬‭2‭*‬ np.pi,‬‭128‬‭),‬


‭init_func=init, blit=‬‭True‬‭)‬‭# blit=True‬‭for faster rendering‬
‭# ani.save('sine_wave.gif', writer='pillow', fps=30)‬
‭plt.show()‬

‭ . Custom Colormaps‬
9
‭Define your own colormaps using LinearSegmentedColormap.from_list()1 or ListedColormap.‬

‭Python‬

‭from‬‭matplotlib.colors‬‭import‬‭LinearSegmentedColormap‬
‭ olors = [‬‭"red"‬‭,‬‭"orange"‬‭,‬‭"yellow"‬‭,‬‭"green"‬‭,‬‭"blue"‬‭]‬‭# Define colors‬
c
‭my_cmap = LinearSegmentedColormap.from_list(‬‭"mycmap"‬‭,‬‭colors)‬
‭plt.imshow(np.random.rand(‬‭10‬‭,‬‭10‬‭), cmap=my_cmap)‬
‭plt.colorbar()‬
‭plt.show()‬

‭How to Discover More Methods‬


‭Matplotlib's API is very extensive. Here's how you can explore it further:‬
‭1.‬ ‭Use dir() and help():‬
‭Python‬
‭import‬‭matplotlib.pyplot‬‭as‬‭plt‬
‭fig, ax = plt.subplots()‬

‭ See all methods/attributes of the Axes object‬


#
‭# print(dir(ax))‬

‭ Get help on a specific method‬


#
‭# help(ax.plot)‬
‭# help(fig.colorbar)‬

‭2.‬ O ‭ fficial Documentation:‬‭The Matplotlib official documentation‬‭is extremely thorough‬


‭and well-organized. It's the ultimate resource.‬
‭○‬ ‭Matplotlib Pyplot API‬
‭○‬ ‭Matplotlib Axes API‬
‭○‬ ‭Matplotlib Figure API‬
‭○‬ ‭Matplotlib Tutorials‬
‭3.‬ ‭Source Code:‬‭For the truly curious, reading the source‬‭code can reveal nuances.‬

‭ his expanded cheat sheet should provide a strong foundation for both basic and advanced‬
T
‭Matplotlib usage. Remember that practice is key to mastering this powerful visualization‬
‭library!‬
‭You're asking for a very comprehensive list of Matplotlib methods, covering basic to advanced‬
‭topics! Matplotlib is vast, with many methods belonging to different objects like‬
‭matplotlib.pyplot, Figure, Axes, Axis, Line2D, Text, etc.‬
‭Instead of an exhaustive, unreadable list of‬‭every‬‭single method‬‭(which would be thousands‬
‭and not practical for a cheat sheet), I'll organize this into common tasks and concepts,‬
‭highlighting the most frequently used and important methods for each. I'll focus on the‬
‭Object-Oriented (OO) interface, as it provides more control and is generally recommended for‬
‭serious plotting.‬

‭This will serve as a much more useful and actionable cheat sheet.‬

‭Matplotlib Cheat Sheet: Methods & Advanced Topics‬


‭Key Objects in Matplotlib's Object-Oriented Interface:‬
‭●‬ F ‭ igure‬‭: The top-level container for all the plot elements.‬‭It's like the canvas. You create it‬
‭with plt.figure() or implicitly with plt.subplots().‬
‭●‬ ‭Axes‬‭: The actual plotting area where data is displayed.‬‭A Figure can contain multiple‬
‭Axes. This is the most frequently interacted-with object for plotting.‬
‭●‬ ‭Axis‬‭: Represents the x-axis and y-axis (or z-axis‬‭in 3D). Each Axes object has xaxis and‬
‭yaxis attributes (e.g., ax.xaxis).‬
‭●‬ A
‭ rtist‬‭: The base class for all objects drawn on a Figure (lines, text, patches, etc.). All of‬
‭the above are Artist subclasses.‬

‭I. Core Setup & Management (Pyplot & Figure Methods)‬


‭Purpose:‬‭Creating and managing the overall plot window‬‭and its fundamental properties.‬

‭1. Creating Figures and Axes‬


‭●‬ p ‭ lt.figure(figsize=(width, height), dpi=None, facecolor=None, edgecolor=None,‬
‭**kwargs): Creates a new Figure.‬
‭○‬ ‭figsize: Tuple (width, height) in inches.‬
‭○‬ ‭dpi: Dots per inch (resolution).‬
‭○‬ ‭facecolor, edgecolor: Background and border colors of the figure.‬
‭●‬ ‭plt.subplots(nrows=1, ncols=1, figsize=None, sharex=False, sharey=False, squeeze=True,‬
‭subplot_kw=None, gridspec_kw=None, **fig_kw): The most common way to create a‬
‭Figure and a set of subplots (Axes).‬
‭○‬ ‭Returns‬‭(fig, ax)‬‭for a single subplot, or‬‭(fig, axs)‬‭where‬‭axs‬‭is a‬‭2‬ ‭NumPy array of Axes‬
‭objects for multiple subplots.‬
‭○‬ ‭sharex, sharey: Share x or y axes among subplots.‬
‭●‬ ‭fig.add_axes(rect): Adds an Axes to the Figure at a specified position [left, bottom, width,‬
‭height] in figure coordinates (0 to 1). Provides precise control over placement.‬
‭●‬ ‭fig.add_subplot(nrows, ncols, index, **kwargs): Adds a single subplot to the figure similar‬
‭to plt.subplot(). Less flexible than plt.subplots().‬
‭●‬ ‭fig.add_gridspec(nrows=1, ncols=1, **kwargs): Returns a GridSpec object, useful for‬
‭complex subplot layouts.‬

‭Examples:‬

‭Python‬

‭import‬‭matplotlib.pyplot‬‭as‬‭plt‬
‭import‬‭numpy‬‭as‬‭np‬

‭# 1. Using plt.figure() and fig.add_subplot() (older style, more manual)‬


‭fig1 = plt.figure(figsize=(‬‭6‭,‬‬‭4‬‭), facecolor=‬‭'lightblue'‬‭)‬
‭ x1 = fig1.add_subplot(‬‭111‬‭)‬‭# 1 row, 1 col, 1st subplot‬
a
‭ax1.plot([‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ , [‬‭4‭,‬‬‭5‬‭,‬‭6‬‭])‬
‭ax1.set_title(‬‭"Manual Subplot Creation"‬‭)‬
‭fig1.suptitle(‬‭"Figure Title for Fig1"‬‭)‬
‭# 2. Using plt.subplots() (recommended for most cases)‬
‭fig2, ax2 = plt.subplots(figsize=(‬‭7‬‭,‬‭5‭)‬ )‬‭# Single‬‭subplot‬
‭ x2.scatter(np.random.rand(‬‭50‬‭), np.random.rand(‬‭50‬‭))‬
a
‭ax2.set_title(‬‭"Single Subplot (plt.subplots)"‬‭)‬

‭# 3. Multiple Subplots with plt.subplots()‬


‭fig3, axs = plt.subplots(‬‭2‬‭,‬‭2‬‭, figsize=(‬‭10‬‭,‬‭8‬‭), sharex=‬‭True‬‭,‬‭sharey=‬‭True‬‭)‬‭# 2x2 grid‬
‭ xs[‬‭0‬‭,‬‭0‭]‬ .plot(np.sin(np.linspace(‬‭0‭,‬‬‭2‭*‬ np.pi,‬‭50‬‭)))‬
a
‭axs[‬‭0‬‭,‬‭0‭]‬ .set_title(‬‭"Sine Wave"‬‭)‬

‭ xs[‬‭0‬‭,‬‭1‭]‬ .hist(np.random.randn(‬‭100‬‭), bins=‬‭10‬‭)‬


a
‭axs[‬‭0‬‭,‬‭1‭]‬ .set_title(‬‭"Histogram"‬‭)‬

‭ xs[‬‭1‬‭,‬‭0‭]‬ .bar([‬‭'A'‬‭,‬‭'B'‬‭,‬‭'C'‬‭], [‬‭10‬‭,‬‭20‬‭,‬‭15‬‭])‬


a
‭axs[‬‭1‬‭,‬‭0‭]‬ .set_title(‬‭"Bar Chart"‬‭)‬

‭ xs[‬‭1‬‭,‬‭1‬‭].scatter(np.random.rand(‬‭20‬‭), np.random.rand(‬‭20‬‭))‬
a
‭axs[‬‭1‬‭,‬‭1‬‭].set_title(‬‭"Scatter Plot"‬‭)‬

‭ g3.suptitle(‬‭"Grid of Subplots"‬‭, fontsize=‬‭16‬‭)‬


fi
‭plt.tight_layout(rect=[‬‭0‭,‬‬‭0‭,‬‬‭1‭,‬‬‭0.96‬‭])‬‭# Adjust layout,‬‭leaving space for suptitle‬

‭# 4. Using fig.add_axes for arbitrary placement‬


‭fig4 = plt.figure(figsize=(‬‭8‭,‬‬‭6‬‭))‬
‭ x_main = fig4.add_axes([‬‭0.1‬‭,‬‭0.1‬‭,‬‭0.8‬‭,‬‭0.8‬‭])‬‭# Main‬‭plot‬
a
‭ax_inset = fig4.add_axes([‬‭0.6‬‭,‬‭0.6‬‭,‬‭0.2‬‭,‬‭0.2‬‭])‬‭# Inset‬‭plot‬

‭ x_main.plot(np.linspace(‬‭0‭,‬‬‭10‬‭,‬‭100‬‭), np.sin(np.linspace(‬‭0‭,‬‬‭10‬‭,‬‭100‬‭)) +‬
a
‭np.random.randn(‬‭100‬‭)*‬‭0.1‬‭)‬
‭ax_main.set_title(‬‭"Main Plot"‬‭)‬

‭ x_inset.plot(np.linspace(‬‭0‬‭,‬‭1‬‭,‬‭20‬‭), np.cos(np.linspace(‬‭0‬‭,‬‭1‬‭,‬‭20‬‭)), color=‬‭'red'‬‭)‬


a
‭ax_inset.set_title(‬‭"Inset"‬‭)‬
‭ax_inset.set_xticks([])‬‭# Remove ticks for cleaner‬‭inset‬
‭ax_inset.set_yticks([])‬

‭plt.show()‬

‭2. Displaying and Saving‬


‭‬ p
● ‭ lt.show(): Displays all open figures. Essential to call at the end of your script.‬
‭●‬ ‭plt.savefig(fname, dpi=None, format=None, bbox_inches='tight', pad_inches=0.1,‬
*‭ *kwargs) or fig.savefig(...): Saves the current (or specified) figure.‬
‭○‬ ‭fname: File path (e.g., 'my_plot.png', 'report.pdf').‬
‭○‬ ‭dpi: Resolution in dots per inch.‬
‭○‬ ‭format: File format (e.g., 'png', 'pdf', 'svg', 'jpeg'). Inferred from fname if not given.‬
‭○‬ ‭bbox_inches='tight': Tries to make the bounding box of the figure tight to the plot‬
‭contents.‬
‭‬
● ‭plt.close(fig=None): Closes the current figure, or a specific figure if fig is passed.‬
‭●‬ ‭plt.close('all'): Closes all figures.‬
‭●‬ ‭plt.clf(): Clears the current figure's axes.‬
‭●‬ ‭fig.clear(): Clears the entire figure (all artists including axes).‬

‭Examples:‬

‭Python‬

‭ g, ax = plt.subplots()‬
fi
‭ax.plot([‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ , [‬‭1‬‭,‬‭4‭,‬‬‭9‬‭])‬
‭ax.set_title(‬‭"Plot to Save"‬‭)‬
‭plt.savefig(‬‭'my_line_plot.png'‬‭, dpi=‬‭300‬‭, bbox_inches=‬‭'tight'‬‭)‬
‭plt.savefig(‬‭'my_line_plot.pdf'‬‭)‬
‭plt.show()‬‭# Display after saving if desired‬
‭plt.close(fig)‬‭# Close this specific figure‬

‭3. Figure Titles and Layout‬


‭‬
● ‭ g.suptitle(t, **kwargs): Adds a centered title to the Figure.‬
fi
‭●‬ ‭fig.supxlabel(s, **kwargs): Adds a centered x-label to the Figure.‬
‭●‬ ‭fig.supylabel(s, **kwargs): Adds a centered y-label to the Figure.‬
‭●‬ ‭plt.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None): Automatically adjusts‬
‭subplot parameters for a tight layout.‬
‭●‬ ‭fig.set_size_inches(width, height): Sets the figure size in inches.‬
‭ ‬ ‭fig.set_dpi(dpi): Sets the figure's resolution.‬

‭Example:‬

‭Python‬

‭fig, (ax1, ax2) = plt.subplots(‬‭1‬‭,‬‭2‬‭, figsize=(‬‭10‬‭,‬‭4‭)‬ )‬


‭ x1.plot([‬‭1‭,‬‬‭2‭]‬ , [‬‭3‭,‬‬‭4‭]‬ )‬
a
‭ax2.plot([‬‭5‬‭,‬‭6‬‭], [‬‭7‬‭,‬‭8‭]‬ )‬
‭fig.suptitle(‬‭'Overall Plot Analysis'‬‭, fontsize=‬‭18‬‭,‬‭color=‬‭'darkblue'‬‭)‬
‭ax1.set_title(‬‭'Left Subplot'‬‭)‬
‭ax2.set_title(‬‭'Right Subplot'‬‭)‬
‭plt.tight_layout(rect=[‬‭0‭,‬‬‭0‭,‬‬‭1‭,‬‬‭0.95‬‭])‬‭# Adjust rect‬‭to leave space for suptitle‬
‭plt.show()‬

‭II. Basic Plotting (Axes Methods)‬


‭ urpose:‬‭Creating common plot types and setting fundamental‬‭visual properties within an‬
P
‭Axes.‬

‭1. Line Plots‬


‭●‬ a
‭ x.plot(*args, **kwargs): Plots y versus x as lines and/or markers.‬
‭○‬ ‭color, c: Line color.‬
‭○‬ ‭linestyle, ls: Line style (e.g., '-', '--', ':', '-.').‬
‭○‬ ‭linewidth, lw: Line width.‬
‭○‬ ‭marker: Marker style (e.g., 'o', 's', '^', 'x', '+').‬
‭○‬ ‭markersize, ms: Marker size.‬
‭○‬ ‭alpha: Transparency (0.0 to 1.0).‬
‭○‬ ‭label: Label for the legend.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots()‬
fi
‭x = np.linspace(‬‭0‭,‬‬‭10‬‭,‬‭100‬‭)‬
‭y1 = np.sin(x)‬
‭y2 = np.cos(x)‬
‭ax.plot(x, y1, label=‬‭'Sine'‬‭, color=‬‭'blue'‬‭, linestyle=‬‭'-'‬‭,‬‭linewidth=‬‭2‭)‬ ‬
‭ax.plot(x, y2, label=‬‭'Cosine'‬‭, color=‬‭'red'‬‭, linestyle=‬‭'--'‬‭,‬‭marker=‬‭'o'‬‭, markersize=‬‭4‬‭)‬
‭ax.set_title(‬‭"Line Plots with Customization"‬‭)‬
‭ax.set_xlabel(‬‭"X-axis"‬‭)‬
‭ax.set_ylabel(‬‭"Y-axis"‬‭)‬
‭ax.legend()‬
‭plt.show()‬
‭2. Scatter Plots‬
‭●‬ a
‭ x.scatter(x, y, s=None, c=None, marker=None, cmap=None, alpha=None,‬
‭edgecolors=None, **kwargs): Creates a scatter plot.‬
‭○‬ ‭s: Marker size (can be a single value or an array).‬
‭○‬ ‭c: Marker color (can be a single value or an array for colormapping).‬
‭○‬ ‭cmap: Colormap to use if c is an array.‬
‭○‬ ‭edgecolors: Color of the marker edges.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots()‬
fi
‭np.random.seed(‬‭42‬‭)‬
‭x_data = np.random.rand(‬‭50‬‭) *‬‭10‬
‭y_data = np.random.rand(‬‭50‬‭) *‬‭10‬
‭sizes = np.random.rand(‬‭50‬‭) *‬‭800‬‭+‬‭50‬‭# Varying sizes‬
‭colors = np.random.rand(‬‭50‬‭)‬‭# Varying colors‬

s‭ catter = ax.scatter(x_data, y_data, s=sizes, c=colors, cmap=‬‭'viridis'‬‭, alpha=‬‭0.7‬‭,‬


‭edgecolors=‬‭'black'‬‭)‬
‭ax.set_title(‬‭"Customized Scatter Plot"‬‭)‬
‭ax.set_xlabel(‬‭"Feature X"‬‭)‬
‭ax.set_ylabel(‬‭"Feature Y"‬‭)‬
‭fig.colorbar(scatter, label=‬‭"Color Value"‬‭)‬
‭plt.show()‬

‭3. Bar Charts‬


‭‬ a
● ‭ x.bar(x, height, width=0.8, bottom=None, align='center', **kwargs): Vertical bar chart.‬
‭●‬ ‭ax.barh(y, width, height=0.8, left=None, align='center', **kwargs): Horizontal bar chart.‬
‭○‬ ‭color: Bar color.‬
‭○‬ ‭edgecolor: Border color of bars.‬
‭○‬ ‭tick_label: Labels for the x-axis ticks (for vertical bars).‬
‭○‬ ‭label: Label for the legend.‬

‭Example:‬
‭Python‬

‭ g, (ax1, ax2) = plt.subplots(‬‭1‬‭,‬‭2‬‭, figsize=(‬‭10‬‭,‬‭4‭)‬ )‬


fi
‭categories = [‬‭'Cat A'‬‭,‬‭'Cat B'‬‭,‬‭'Cat C'‬‭,‬‭'Cat D'‬‭]‬
‭values = [‬‭15‬‭,‬‭28‬‭,‬‭22‬‭,‬‭35‬‭]‬

‭ x1.bar(categories, values, color=[‬‭'skyblue'‬‭,‬‭'lightcoral'‬‭,‬‭'lightgreen'‬‭,‬‭'gold'‬‭], edgecolor=‬‭'gray'‬‭)‬


a
‭ax1.set_title(‬‭"Vertical Bar Chart"‬‭)‬
‭ax1.set_ylabel(‬‭"Quantity"‬‭)‬
‭ax1.set_xlabel(‬‭"Category"‬‭)‬

‭# Stacked Bar Chart‬


‭labels_stacked = [‬‭'Group 1'‬‭,‬‭'Group 2'‬‭,‬‭'Group 3'‬‭]‬
v‭ al1 = [‬‭20‬‭,‬‭35‬‭,‬‭30‬‭]‬
‭val2 = [‬‭15‬‭,‬‭20‬‭,‬‭25‬‭]‬
‭ax2.bar(labels_stacked, val1, label=‬‭'Series 1'‬‭, color=‬‭'lightgray'‬‭)‬
‭ax2.bar(labels_stacked, val2, bottom=val1, label=‬‭'Series‬‭2'‬‭, color=‬‭'darkgray'‬‭)‬‭# Stack on top of val1‬
‭ax2.set_title(‬‭"Stacked Bar Chart"‬‭)‬
‭ax2.legend()‬
‭plt.tight_layout()‬
‭plt.show()‬

‭4. Histograms‬
‭●‬ a
‭ x.hist(x, bins=10, range=None, density=False, cumulative=False, histtype='bar',‬
‭align='mid', orientation='vertical', rwidth=None, log=False, **kwargs): Plots a histogram.‬
‭○‬ ‭bins: Number of bins or a sequence defining bin edges.‬
‭○‬ ‭density: If True, normalize to form a probability density.‬
‭○‬ ‭histtype: 'bar', 'barstacked', 'step', 'stepfilled'.‬
‭○‬ ‭edgecolor: Color of bin edges.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots(figsize=(‬‭8‭,‬‬‭5‭)‬ )‬
fi
‭data = np.random.normal(loc=‬‭0‬‭, scale=‬‭1‭,‬ size=‬‭1000‬‭)‬‭# Normally distributed data‬
‭ax.hist(data, bins=‬‭50‬‭, color=‬‭'teal'‬‭, edgecolor=‬‭'black'‬‭,‬‭alpha=‬‭0.7‬‭, density=‬‭True‬‭)‬
‭ax.set_title(‬‭"Histogram of Normal Distribution"‬‭)‬
‭ x.set_xlabel(‬‭"Value"‬‭)‬
a
‭ax.set_ylabel(‬‭"Probability Density"‬‭)‬
‭plt.show()‬

‭5. Pie Charts‬


‭●‬ a
‭ x.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6,‬
‭shadow=False, startangle=None, radius=None, wedgeprops=None, textprops=None,‬
‭frame=False, center=(0, 0), rotatelabels=False, **kwargs): Creates a pie chart.‬
‭○‬ ‭explode: Sequence to "explode" slices.‬
‭○‬ ‭labels: Labels for each wedge.‬
‭○‬ ‭autopct: Format string for percentage labels (e.g., '%.1f%%').‬
‭○‬ ‭shadow: Add a shadow to the pie chart.‬
‭○‬ ‭startangle: Starting angle for the first wedge.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots(figsize=(‬‭7‬‭,‬‭7‭)‬ )‬
fi
‭sizes = [‬‭15‬‭,‬‭30‬‭,‬‭45‬‭,‬‭10‬‭]‬
‭labels = [‬‭'East'‬‭,‬‭'West'‬‭,‬‭'North'‬‭,‬‭'South'‬‭]‬
‭explode = (‬‭0‭,‬‬‭0.1‬‭,‬‭0‭,‬‬‭0‭)‬ ‬‭# Explode the 'West' slice‬

‭ax.pie(sizes, explode=explode, labels=labels, autopct=‬‭'%1.1f%%'‬‭,‬


‭shadow=‬‭True‬‭, startangle=‬‭90‬‭, colors=[‬‭'gold'‬‭,‬‭'yellowgreen'‬‭,‬‭'lightcoral'‬‭,‬‭'lightskyblue'‬‭])‬
‭ax.set_title(‬‭"Regional Sales Distribution"‬‭)‬
‭ax.axis(‬‭'equal'‬‭)‬‭# Equal aspect ratio ensures that‬‭pie is drawn as a circle.‬
‭plt.show()‬

‭III. Plot Customization (Axes & Axis Methods)‬


‭Purpose:‬‭Adding details, labels, titles, and adjusting‬‭the appearance of the plot.‬

‭1. Titles and Labels‬


‭●‬ a ‭ x.set_title(label, loc='center', fontdict=None, pad=None, **kwargs): Sets the title of the‬
‭Axes.‬
‭○‬ ‭loc: Location of the title ('left', 'center', 'right').‬
‭●‬ ‭ax.set_xlabel(label, fontdict=None, labelpad=None, **kwargs): Sets the label for the‬
x‭ -axis.‬
‭●‬ ‭ax.set_ylabel(label, fontdict=None, labelpad=None, **kwargs): Sets the label for the‬
‭y-axis.‬
‭ ‬ ‭ax.text(x, y, s, fontdict=None, **kwargs): Adds arbitrary text to the Axes at data‬

‭coordinates (x, y).‬
‭●‬ ‭ax.annotate(s, xy, xytext, arrowprops=None, **kwargs): Annotates a point xy with text s.‬
‭○‬ ‭xy: The point (x, y) to annotate.‬
‭○‬ ‭xytext: The position (x, y) to place the text.‬
‭○‬ ‭arrowprops: Dictionary of properties for the arrow.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots(figsize=(‬‭8‭,‬‬‭6‬‭))‬
fi
‭x = np.array([‬‭1‭,‬‬‭2‭,‬‬‭3‭,‬‬‭4‭,‬‬‭5‬‭])‬
‭y = np.array([‬‭2‭,‬‬‭3‭,‬‬‭5‭,‬‬‭4‭,‬‬‭6‬‭])‬
‭ax.plot(x, y,‬‭'bo-'‬‭)‬
‭ax.set_title(‬‭"Sales Data (2024)"‬‭, loc=‬‭'left'‬‭, fontsize=‬‭16‬‭,‬‭color=‬‭'darkgreen'‬‭)‬
‭ax.set_xlabel(‬‭"Month"‬‭, fontsize=‬‭12‬‭, color=‬‭'gray'‬‭)‬
‭ax.set_ylabel(‬‭"Sales (Units)"‬‭, fontsize=‬‭12‬‭, color=‬‭'gray'‬‭)‬

‭ x.text(‬‭3‭,‬‬‭5.5‬‭,‬‭"Peak Sales!"‬‭, fontsize=‬‭10‬‭, color=‬‭'purple'‬‭,‬‭ha=‬‭'center'‬‭)‬


a
‭ax.annotate(‬‭'Highest Point'‬‭, xy=(‬‭5‬‭,‬‭6‬‭), xytext=(‬‭4‬‭,‬‭6.5‬‭),‬
‭arrowprops=‬‭dict‬‭(facecolor=‬‭'black'‬‭, shrink=‬‭0.05‬‭,‬‭width=‬‭1‭,‬ headwidth=‬‭8‬‭),‬
‭fontsize=‬‭10‬‭, color=‬‭'darkred'‬‭)‬
‭plt.show()‬

‭2. Legends‬
‭●‬ a
‭ x.legend(*args, **kwargs): Places a legend on the Axes.‬
‭○‬ ‭loc: Location (e.g., 'upper right', 'lower left', 'best', (x, y) tuple).‬
‭○‬ ‭fontsize: Font size of legend text.‬
‭○‬ ‭frameon: Whether to draw a frame around the legend.‬
‭○‬ ‭shadow: Add a shadow to the legend box.‬
‭○‬ ‭ncol: Number of columns in the legend.‬
‭○‬ ‭title: Title for the legend.‬

‭Example:‬
‭Python‬

‭ g, ax = plt.subplots()‬
fi
‭x = np.linspace(‬‭0‭,‬‬‭5‬‭,‬‭20‬‭)‬
‭ax.plot(x, x**‬‭2‭,‬ label=‬‭'Quadratic'‬‭, color=‬‭'orange'‬‭)‬
‭ax.plot(x, x**‬‭3‭,‬ label=‬‭'Cubic'‬‭, color=‬‭'green'‬‭, linestyle=‬‭':'‬‭)‬
‭ax.legend(loc=‬‭'upper left'‬‭, fontsize=‬‭'small'‬‭, frameon=‬‭True‬‭,‬‭shadow=‬‭True‬‭, ncol=‬‭1‭,‬ title=‬‭'Functions'‬‭)‬
‭plt.show()‬

‭3. Axis Limits, Ticks, and Scale‬


‭‬
● ‭ x.set_xlim(xmin, xmax): Sets the x-axis view limits.‬
a
‭●‬ ‭ax.set_ylim(ymin, ymax): Sets the y-axis view limits.‬
‭●‬ ‭ax.set_xticks(ticks): Sets the locations of the x-axis ticks.‬
‭●‬ ‭ax.set_xticklabels(labels, rotation=None, ha='center', **kwargs): Sets the labels for x-axis‬
‭ticks.‬
‭‬
● ‭ax.set_yticks(ticks)‬
‭●‬ ‭ax.set_yticklabels(labels, rotation=None, va='center', **kwargs)‬
‭●‬ ‭ax.tick_params(axis='both', which='major', direction='out', length=6, width=2,‬
‭colors='black', labelcolor='blue', labelsize=10, pad=5, labelrotation=0, **kwargs):‬
‭Configures tick properties.‬
‭○‬ ‭axis: Which axis to apply to ('x', 'y', 'both').‬
‭○‬ ‭which: Which ticks ('major', 'minor', 'both').‬
‭○‬ ‭direction: Direction of ticks ('in', 'out', 'inout').‬
‭‬
● ‭ax.minorticks_on(): Displays minor ticks.‬
‭●‬ ‭ax.minorticks_off(): Removes minor ticks.‬
‭●‬ ‭ax.set_xscale('linear'/'log'/'symlog'/'logit'): Sets the x-axis scale.‬
‭●‬ ‭ax.set_yscale('linear'/'log'/'symlog'/'logit'): Sets the y-axis scale.‬
‭●‬ ‭ax.invert_xaxis(): Inverts the x-axis direction.‬
‭●‬ ‭ax.invert_yaxis(): Inverts the y-axis direction.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots(figsize=(‬‭8‭,‬‬‭5‭)‬ )‬
fi
‭x = np.linspace(‬‭1‭,‬‬‭100‬‭,‬‭50‬‭)‬
‭ = np.log(x)‬
y
‭ax.plot(x, y)‬
‭ax.set_xscale(‬‭'log'‬‭)‬‭# Logarithmic x-axis‬
‭ax.set_title(‬‭"Logarithmic Scale Example"‬‭)‬
‭ax.set_xlabel(‬‭"Values (log scale)"‬‭)‬
‭ax.set_ylabel(‬‭"Log(Values)"‬‭)‬

‭# Custom ticks and labels‬


‭ax.set_xticks([‬‭1‭,‬‬‭10‬‭,‬‭100‬‭])‬
‭ x.set_xticklabels([‬‭'1'‬‭,‬‭'10'‬‭,‬‭'100'‬‭], rotation=‬‭45‬‭,‬‭ha=‬‭'right'‬‭)‬
a
‭ax.tick_params(axis=‬‭'y'‬‭, direction=‬‭'inout'‬‭, length=‬‭8‭,‬‬‭colors=‬‭'red'‬‭, labelsize=‬‭10‬‭)‬
‭ax.minorticks_on()‬
‭plt.show()‬

‭4. Grids and Spines‬


‭●‬ a ‭ x.grid(True, which='major', axis='both', linestyle='--', color='gray', alpha=0.6, **kwargs):‬
‭Configures grid lines.‬
‭●‬ ‭ax.spines['left'].set_visible(False): Hides a specific spine (plot border).‬
‭●‬ ‭ax.spines['bottom'].set_color('blue'): Sets the color of a spine.‬
‭●‬ ‭ax.spines['top'].set_linewidth(2): Sets the linewidth of a spine.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots(figsize=(‬‭7‬‭,‬‭5‭)‬ )‬
fi
‭ax.plot(np.random.rand(‬‭10‬‭))‬
‭ax.grid(‬‭True‬‭, which=‬‭'both'‬‭, axis=‬‭'both'‬‭, linestyle=‬‭':'‬‭,‬‭color=‬‭'lightgray'‬‭, alpha=‬‭0.8‬‭)‬‭# Grid‬
‭ax.spines[‬‭'right'‬‭].set_visible(‬‭False‬‭)‬‭# Remove right‬‭spine‬
‭ax.spines[‬‭'top'‬‭].set_visible(‬‭False‬‭)‬ ‭# Remove top‬‭spine‬
‭ax.spines[‬‭'left'‬‭].set_linewidth(‬‭1.5‬‭)‬
‭ax.spines[‬‭'bottom'‬‭].set_linewidth(‬‭1.5‬‭)‬
‭ax.set_title(‬‭"Grid and Spines Customization"‬‭)‬
‭plt.show()‬

‭5. Background and Facecolor‬


‭ ‬ fi
● ‭ g.set_facecolor(color): Sets the background color of the Figure.‬
‭●‬ ‭ax.set_facecolor(color): Sets the background color of the Axes (plot area).‬
‭Example:‬

‭Python‬

‭ g, ax = plt.subplots(figsize=(‬‭6‬‭,‬‭4‭)‬ )‬
fi
‭fig.set_facecolor(‬‭'#F0F0F0'‬‭)‬‭# Light grey for figure‬
‭ax.set_facecolor(‬‭'#E0F7FA'‬‭)‬ ‭# Light blue for axes‬
‭ax.plot([‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ , [‬‭4‬‭,‬‭5‬‭,‬‭6‬‭], color=‬‭'darkblue'‬‭)‬
‭ax.set_title(‬‭"Custom Background Colors"‬‭)‬
‭plt.show()‬

‭IV. Advanced Topics & Specialized Plots‬


‭ urpose:‬‭Exploring more complex visualization types,‬‭interactive features, and fine-grained‬
P
‭control.‬

‭1. Colormaps and Colorbars‬


‭‬ m
● ‭ atplotlib.cm: Module for colormaps.‬
‭●‬ ‭plt.cm.get_cmap(name): Get a colormap by name.‬
‭●‬ ‭fig.colorbar(mappable, ax=None, shrink=1.0, aspect=20, orientation='vertical',‬
‭label=None, **kwargs): Adds a colorbar to the figure.‬
‭○‬ ‭mappable: The plot object (ax.scatter, ax.imshow, ax.pcolormesh, etc.) that the‬
‭colorbar represents.‬
‭○‬ ‭ax: The Axes to which the colorbar should be attached.‬

‭Example:‬

‭Python‬

‭ g, ax = plt.subplots(figsize=(‬‭8‭,‬‬‭6‬‭))‬
fi
‭x = np.random.rand(‬‭100‬‭) *‬‭10‬
‭y = np.random.rand(‬‭100‬‭) *‬‭10‬
‭values = x + y + np.random.randn(‬‭100‬‭) *‬‭5‬

‭scatter = ax.scatter(x, y, c=values, cmap=‬‭'RdYlGn'‬‭,‬‭s=‬‭100‬‭, alpha=‬‭0.8‬‭, edgecolors=‬‭'black'‬‭)‬


‭ x.set_title(‬‭"Scatter Plot with Colorbar"‬‭)‬
a
‭fig.colorbar(scatter, ax=ax, label=‬‭"Value Scale"‬‭,‬‭orientation=‬‭'vertical'‬‭)‬
‭plt.show()‬

‭2. Heatmaps and Contour Plots‬


‭●‬ a ‭ x.imshow(Z, cmap='viridis', aspect='auto', interpolation='nearest', origin='upper',‬
‭extent=None, **kwargs): Displays data as an image (matrix of values).‬
‭○‬ ‭Z: 2D array of data.‬
‭○‬ ‭interpolation: How to interpolate between pixels ('nearest', 'bilinear', 'bicubic').‬
‭●‬ ‭ax.contour(X, Y, Z, levels=None, colors=None, **kwargs): Creates contour lines.‬
‭●‬ ‭ax.contourf(X, Y, Z, levels=None, cmap=None, **kwargs): Creates filled contour regions.‬
‭○‬ ‭X, Y: 2D arrays of coordinates (from np.meshgrid).‬
‭○‬ ‭Z: 2D array of values.‬
‭○‬ ‭levels: Number of contour levels or a sequence of levels.‬

‭Example:‬

‭Python‬

‭from‬‭scipy.stats‬‭import‬‭multivariate_normal‬
‭fig, (ax1, ax2) = plt.subplots(‬‭1‬‭,‬‭2‬‭, figsize=(‬‭12‬‭,‬‭5‬‭))‬

‭# Generate 2D Gaussian data‬


x‭ _mesh, y_mesh = np.mgrid[-‬‭2‭:‬‭2‬ ‬‭:‭.‬01‬‭, -‬‭2‭:‬‭2‬ ‭:‬‬‭.01‬‭]‬
‭pos = np.empty(x_mesh.shape + (‬‭2‭,‬))‬
‭pos[:, :,‬‭0‬‭] = x_mesh; pos[:, :,‬‭1‭]‬ = y_mesh‬
‭rv = multivariate_normal([‬‭0‬‭,‬‭0‭]‬ , [[‬‭0.5‬‭,‬‭0‭]‬ , [‬‭0‬‭,‬‭0.5‬‭]])‬
‭z_data = rv.pdf(pos)‬

‭# Heatmap‬
i‭m = ax1.imshow(z_data, cmap=‬‭'hot'‬‭, origin=‬‭'lower'‬‭,‬‭extent=[-‬‭2‭,‬‬‭2‭,‬ -‬‭2‭,‬‬‭2‭]‬ )‬
‭ax1.set_title(‬‭"Heatmap"‬‭)‬
‭fig.colorbar(im, ax=ax1)‬

‭# Contour Plot‬
‭ ontour = ax2.contour(x_mesh, y_mesh, z_data, levels=‬‭10‬‭,‬‭colors=‬‭'black'‬‭, linewidths=‬‭0.8‬‭)‬
c
‭ax2.contourf(x_mesh, y_mesh, z_data, levels=‬‭10‬‭, cmap=‬‭'Blues'‬‭,‬‭alpha=‬‭0.7‬‭)‬
‭ax2.clabel(contour, inline=‬‭1‬‭, fontsize=‬‭8‬‭)‬‭# Add labels‬‭to contour lines‬
‭ax2.set_title(‬‭"Contour Plot"‬‭)‬
‭ lt.tight_layout()‬
p
‭plt.show()‬

‭3. 3D Plots (mpl_toolkits.mplot3d)‬


‭‬
● ‭ equires from mpl_toolkits.mplot3d import Axes3D.‬
R
‭●‬ ‭fig.add_subplot(projection='3d'): Key to creating a 3D Axes.‬
‭●‬ ‭ax.plot_surface(X, Y, Z, cmap='viridis', **kwargs): Plots a 3D surface.‬
‭●‬ ‭ax.plot_wireframe(X, Y, Z, **kwargs): Plots a 3D wireframe.‬
‭●‬ ‭ax.scatter(xs, ys, zs, **kwargs): Plots points in 3D.‬
‭●‬ ‭ax.plot(xs, ys, zs, **kwargs): Plots lines in 3D.‬
‭●‬ ‭ax.set_zlabel(label): Sets the z-axis label.‬

‭Example:‬

‭Python‬

‭from‬‭mpl_toolkits.mplot3d‬‭import‬‭Axes3D‬

‭ g = plt.figure(figsize=(‬‭10‬‭,‬‭7‬‭))‬
fi
‭ax = fig.add_subplot(‬‭111‬‭, projection=‬‭'3d'‬‭)‬

‭# Create data for 3D plot‬


‭X = np.arange(-‬‭5‬‭,‬‭5‭,‬‬‭0.25‬‭)‬
‭ = np.arange(-‬‭5‬‭,‬‭5‭,‬‬‭0.25‬‭)‬
Y
‭X, Y = np.meshgrid(X, Y)‬
‭R = np.sqrt(X**‬‭2‬‭+ Y**‬‭2‭)‬ ‬
‭Z = np.sin(R)‬

‭ x.plot_surface(X, Y, Z, cmap=‬‭'coolwarm'‬‭, rstride=‬‭1‭,‬‬‭cstride=‬‭1‬‭, alpha=‬‭0.8‬‭)‬


a
‭ax.set_xlabel(‬‭'X'‬‭)‬
‭ax.set_ylabel(‬‭'Y'‬‭)‬
‭ax.set_zlabel(‬‭'Z'‬‭)‬
‭ax.set_title(‬‭"3D Surface Plot of a Sombrero Function"‬‭)‬
‭plt.show()‬

‭4. Twin Axes‬


‭‬ a
● ‭ x.twinx(): Creates a twin Axes sharing the x-axis.‬
‭●‬ ‭ax.twiny(): Creates a twin Axes sharing the y-axis.‬
‭Example:‬

‭Python‬

‭fig, ax1 = plt.subplots(figsize=(‬‭9‬‭,‬‭5‭)‬ )‬

x‭ = np.linspace(‬‭0‭,‬‬‭10‬‭,‬‭50‬‭)‬
‭data1 = np.exp(x/‬‭2‭)‬ ‬‭# Exponential growth‬
‭data2 = x *‬‭10‬ ‭# Linear growth‬

‭ olor1 =‬‭'tab:red'‬
c
‭ax1.set_xlabel(‬‭'Time (s)'‬‭)‬
‭ax1.set_ylabel(‬‭'Temperature (°C)'‬‭, color=color1)‬
‭ax1.plot(x, data1, color=color1, label=‬‭'Temperature'‬‭)‬
‭ax1.tick_params(axis=‬‭'y'‬‭, labelcolor=color1)‬

‭ x2 = ax1.twinx()‬‭# Create a second Axes that shares‬‭the same x-axis‬


a
‭color2 =‬‭'tab:blue'‬
‭ax2.set_ylabel(‬‭'Pressure (kPa)'‬‭, color=color2)‬
‭ax2.plot(x, data2, color=color2, linestyle=‬‭'--'‬‭, label=‬‭'Pressure'‬‭)‬
‭ax2.tick_params(axis=‬‭'y'‬‭, labelcolor=color2)‬

‭fig.suptitle(‬‭'Temperature and Pressure over Time'‬‭)‬


‭# Combine legends from both axes‬
l‭ines1, labels1 = ax1.get_legend_handles_labels()‬
‭lines2, labels2 = ax2.get_legend_handles_labels()‬
‭ax2.legend(lines1 + lines2, labels1 + labels2, loc=‬‭'upper‬‭left'‬‭)‬

‭ lt.tight_layout()‬
p
‭plt.show()‬

‭5. Animations‬
‭●‬ m ‭ atplotlib.animation.FuncAnimation: Creates an animation by repeatedly calling a‬
‭function.‬
‭●‬ ‭matplotlib.animation.ArtistAnimation: Creates an animation using a fixed set of Artist‬
‭objects.‬

‭Example (Simple Sine Wave Animation):‬


‭Python‬

‭from‬‭matplotlib.animation‬‭import‬‭FuncAnimation‬

‭ g, ax = plt.subplots(figsize=(‬‭7‬‭,‬‭5‭)‬ )‬
fi
‭xdata, ydata = [], []‬
‭ln, = ax.plot([], [],‬‭'r-'‬‭)‬

‭def‬‭init‬‭():‬
‭ x.set_xlim(‬‭0‬‭,‬‭2‭*‬ np.pi)‬
a
‭ax.set_ylim(-‬‭1.1‬‭,‬‭1.1‬‭)‬
‭return‬‭ln,‬

‭def‬‭update‬‭(frame):‬
x‭ data.append(frame)‬
‭ydata.append(np.sin(frame))‬
‭ln.set_data(xdata, ydata)‬
‭return‬‭ln,‬

‭# interval: delay between frames in ms, blit: optimize drawing‬


‭ani = FuncAnimation(fig, update, frames=np.linspace(‬‭0‬‭,‬‭2‭*‬ np.pi,‬‭128‬‭),‬
‭init_func=init, blit=‬‭True‬‭, interval‬‭=‭2‬ 0‬‭)‬
‭ To save the animation:‬
#
‭# ani.save('sine_wave.gif', writer='imagemagick', fps=30) # Requires imagemagick‬
‭# ani.save('sine_wave.mp4', writer='ffmpeg', fps=30) # Requires ffmpeg‬

‭plt.show()‬

‭6. Event Handling & Interactivity‬‭3‬


‭●‬ fi ‭ g.canvas.mpl_connect(event, callback_function): Connects to a Matplotlib event (e.g.,‬
‭'button_press_event', 'key_press_event', 'motion_notify_event').‬
‭●‬ ‭fig.canvas.mpl_disconnect(cid): Disconnects an event.‬
‭●‬ ‭plt.ginput(n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3,‬
‭mouse_stop=2): Get mouse input from a figure.‬

‭Example (Click to add points):‬

‭Python‬
‭def‬‭onclick‬‭(event):‬
‭if‬‭event.xdata‬‭is‬‭not‬‭None‬‭and‬‭event.ydata‬‭is‬‭not‬‭None‬‭:‬
‭ rint(‬‭f"Clicked at: x=‬‭{event.xdata:‬‭.2‬‭f}‬‭, y=‬‭{event.ydata:‬‭.2‬‭f}‬‭"‭)‬ ‬
p
‭ax.plot(event.xdata, event.ydata,‬‭'ro'‬‭, markersize=‬‭8‭)‬ ‬
‭fig.canvas.draw_idle()‬‭# Redraw the figure‬

‭ g, ax = plt.subplots(figsize=(‬‭7‬‭,‬‭5‭)‬ )‬
fi
‭ax.set_title(‬‭"Click anywhere to add a red point"‬‭)‬
‭cid = fig.canvas.mpl_connect(‬‭'button_press_event'‬‭,‬‭onclick)‬
‭plt.show()‬

‭# To disconnect: fig.canvas.mpl_disconnect(cid)‬

‭ . Custom Projections‬
7
‭Matplotlib allows for custom projections beyond standard 2D and 3D. This is a very advanced‬
‭topic, involving creating custom Projection classes. Common examples include polar plots‬
‭(which are built-in) and various geographical map projections.‬
‭●‬ ‭fig.add_subplot(projection='polar'): Creates a polar plot Axes.‬

‭Example (Polar Plot):‬

‭Python‬

‭ g = plt.figure(figsize=(‬‭7‭,‬‬‭7‬‭))‬
fi
‭ax = fig.add_subplot(‬‭111‬‭, projection=‬‭'polar'‬‭)‬

r‭ = np.arange(‬‭0‭,‬‬‭2‭,‬‬‭0.01‬‭)‬
‭theta =‬‭2‬‭* np.pi * r‬

‭ x.plot(theta, r, color=‬‭'blue'‬‭, linewidth=‬‭2‭)‬ ‬


a
‭ax.set_title(‬‭"Polar Plot"‬‭, va=‬‭'bottom'‬‭)‬
‭ax.set_rticks([‬‭0.5‬‭,‬‭1‭,‬‬‭1.5‬‭,‬‭2‭]‬ )‬‭# Radial tick marks‬
‭ax.grid(‬‭True‬‭)‬
‭plt.show()‬

‭ . Customizing Matplotlib Defaults (rcParams)‬


8
‭You can change the default behavior of Matplotlib globally or for specific plots using‬
‭rcParams.‬
‭‬ p
● ‭ lt.rcParams['key'] = value: Sets a global default.‬
‭●‬ ‭plt.rc('key', value): Another way to set defaults.‬

‭Example:‬

‭Python‬

‭# Save current rcParams to restore later‬


‭original_rc_params = plt.rcParams.copy()‬

‭# Change default line color and linewidth‬


‭plt.rcParams[‬‭'lines.color'‬‭] =‬‭'green'‬
‭ lt.rcParams[‬‭'lines.linewidth'‬‭] =‬‭3‬
p
‭plt.rcParams[‬‭'font.family'‬‭] =‬‭'serif'‬
‭plt.rcParams[‬‭'font.serif'‬‭] = [‬‭'Times New Roman'‬‭]‬‭#‬‭Or any other serif font‬

‭ g, ax = plt.subplots(figsize=(‬‭6‬‭,‬‭4‭)‬ )‬
fi
‭ax.plot([‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ , [‬‭4‬‭,‬‭5‬‭,‬‭6‬‭])‬‭# This line will be‬‭green and thicker‬
‭ax.set_title(‬‭"Custom RCParams Example"‬‭)‬
‭plt.show()‬

‭# Restore original settings‬


‭plt.rcParams.update(original_rc_params)‬

‭# Plot again, it will revert to default‬


‭fig, ax = plt.subplots(figsize=(‬‭6‬‭,‬‭4‭)‬ )‬
‭ x.plot([‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ , [‬‭4‬‭,‬‭5‬‭,‬‭6‬‭])‬
a
‭ax.set_title(‬‭"Restored RCParams Example"‬‭)‬
‭plt.show()‬

‭ his extended cheat sheet covers a broad range of Matplotlib methods and advanced topics,‬
T
‭focusing on practical usage with examples. Remember that the official Matplotlib‬
‭documentation is always the most authoritative and detailed resource for any specific method‬
‭or advanced concept. Happy plotting!‬

‭ ources‬
S
‭1.‬‭https://github.com/dragontree101/TensorFlow-study-cn‬
‭2.‬‭https://www.yzktw.com.cn/post/1227619.html‬
‭3.‬‭http://www.mynw.cn/cloud/15213.html‬
‭4.‬‭https://github.com/alexdumitriu/AstroStuff‬
‭5.‬‭https://github.com/ddemetriou21/python-data-handling‬

You might also like