### Setup for pcolormesh examples Source: https://matplotlib.org/stable/gallery/images_contours_and_fields/pcolormesh_grids.html Imports necessary libraries and defines plotting parameters. This setup is common across multiple examples. ```python import matplotlib.pyplot as plt import numpy as np ``` -------------------------------- ### Get verbose installation details Source: https://matplotlib.org/stable/users/faq.html Use this command to output detailed platform information during installation. ```bash pip install --verbose ``` -------------------------------- ### Example Installation Output Source: https://matplotlib.org/stable/install/index.html Expected output format when verifying a successful Matplotlib installation. ```text 3.10.0 /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/__init__.py ``` -------------------------------- ### Initialize Example Data Source: https://matplotlib.org/stable/_downloads/4a8db41bb850567e9fd7e426f443dba4/subplots_demo.ipynb Setup code for generating sample data used in subsequent plotting examples. ```python import matplotlib.pyplot as plt import numpy as np # Some example data to display x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) ``` -------------------------------- ### Setup for Marker Examples Source: https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html Imports necessary modules and defines helper functions for formatting axes and splitting lists, used across various marker examples. ```python import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.markers import MarkerStyle from matplotlib.transforms import Affine2D text_style = dict(horizontalalignment='right', verticalalignment='center', fontsize=12, fontfamily='monospace') marker_style = dict(linestyle=':', color='0.8', markersize=10, markerfacecolor="tab:blue", markeredgecolor="tab:blue") def format_axes(ax): ax.margins(0.2) ax.set_axis_off() ax.invert_yaxis() def split_list(a_list): i_half = len(a_list) // 2 return a_list[:i_half], a_list[i_half:] ``` -------------------------------- ### Linking to Documentation Pages Source: https://matplotlib.org/stable/devel/document.html Use the `:doc:` role with absolute paths (starting with '/') to cross-link to other pages in the documentation. This ensures clear navigation to specific sections like installation guides. ```rst See the :doc:`/install/index` ``` -------------------------------- ### Cleaned Up Setup Logic in setup.py Source: https://matplotlib.org/stable/users/prev_whats_new/changelog.html The setup script (`setup.py`) has undergone a cleanup of its logic, streamlining the installation and configuration process for Matplotlib. ```python # setup.py: cleaned up setup logic - NN ``` -------------------------------- ### Import Libraries and Setup Source: https://matplotlib.org/stable/gallery/images_contours_and_fields/image_demo.html Imports necessary libraries and sets a random seed for reproducibility. This is a common setup for Matplotlib examples. ```python import matplotlib.pyplot as plt import numpy as np import matplotlib.cbook as cbook import matplotlib.cm as cm from matplotlib.patches import PathPatch from matplotlib.path import Path # Fixing random state for reproducibility np.random.seed(19680801) ``` -------------------------------- ### Setup GTK Toolbar Source: https://matplotlib.org/stable/gallery/user_interfaces/mplcvd.html Configures a GTK toolbar with a dropdown menu for selecting display options. Requires GTK to be installed. ```python def _setup_gtk(tb): from matplotlib.backends.backend_gtk3 import Gtk from pathlib import Path menu = Gtk.Menu() for name in _MENU_ENTRIES: item = Gtk.MenuItem(name) item.connect("activate", lambda w, _name=name: _set_menu_entry(tb, _name)) menu.append(item) menu.show_all() tbutton = Gtk.MenuToolButton.new(image, _BUTTON_NAME) tbutton.set_menu(menu) tb.insert(tbutton, idx + 1) tb.show_all() ``` -------------------------------- ### Import Libraries and Setup Source: https://matplotlib.org/stable/_downloads/baca3c3513a3e3102673c4c4bf6dfd44/colorbar_tick_labelling_demo.ipynb Imports necessary libraries and sets up a random number generator for reproducible data. This is boilerplate code for the examples. ```python import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as mticker # Fixing random state for reproducibility rng = np.random.default_rng(seed=19680801) ``` -------------------------------- ### HTMLWriter.setup() Source: https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.HTMLWriter.html Prepares the environment for writing the movie file, setting up the figure, output file, and DPI. ```APIDOC ## HTMLWriter.setup() ### Description Setup for writing the movie file. ### Parameters * **fig** (`Figure`) - The figure to grab the rendered frames from. * **outfile** (str) - The filename of the resulting movie file. * **dpi** (float) - Optional - The dpi of the output file. This, with the figure size, controls the size in pixels of the resulting movie file. Defaults to `fig.dpi`. * **frame_dir** (str) - Optional - The directory to save temporary frames. ### Method `setup(fig, outfile, dpi=None, frame_dir=None)` ``` -------------------------------- ### Get Matplotlib Install Location Source: https://matplotlib.org/stable/install/index.html Locate the directory where the Matplotlib package is installed. ```python >>> import matplotlib >>> matplotlib.__file__ '/home/jdhunter/dev/lib64/python2.5/site-packages/matplotlib/__init__.pyc' ``` -------------------------------- ### WebAggApplication.start Source: https://matplotlib.org/stable/api/backend_webagg_api.html Starts the WebAggApplication. ```APIDOC ## WebAggApplication.start ### Description Starts the WebAggApplication. ``` -------------------------------- ### MovieWriter.setup Method Source: https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.MovieWriter.html Prepares the MovieWriter for writing by setting up the figure, output file, and DPI. ```APIDOC ## MovieWriter.setup ### Description Setup for writing the movie file. ### Parameters - **fig** (`Figure`) - The figure object that contains the information for frames. - **outfile** (str) - The filename of the resulting movie file. - **dpi** (float, optional) - The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file. Defaults to `fig.dpi`. ``` -------------------------------- ### Setup for Contour Plotting Source: https://matplotlib.org/stable/gallery/images_contours_and_fields/contour_demo.html Initializes numpy arrays and creates a Z matrix for contour plotting. This setup is common for all subsequent examples. ```python import matplotlib.pyplot as plt import numpy as np import matplotlib.cm as cm delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 ``` -------------------------------- ### Basic Grid Configuration Source: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.grid.html Demonstrates how to turn on grid lines with custom properties. This example shows setting color, linestyle, and linewidth for the grid. ```python import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.grid(color='r', linestyle='-', linewidth=2) plt.show() ``` -------------------------------- ### Build HTML Documentation Source: https://matplotlib.org/stable/devel/document.html Navigate to the doc/ directory and run 'make html' to build the documentation in HTML format. The initial build may take a significant amount of time. ```bash make html ``` -------------------------------- ### Setup and Event Connection Source: https://matplotlib.org/stable/gallery/event_handling/pick_event_demo.html Imports necessary libraries and sets up a figure with two subplots. It configures artists for picking and connects a 'pick_event' callback. ```python import matplotlib.pyplot as plt import numpy as np from numpy.random import rand from matplotlib.image import AxesImage from matplotlib.lines import Line2D from matplotlib.patches import Rectangle from matplotlib.text import Text # Fixing random state for reproducibility np.random.seed(19680801) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.set_title('click on points, rectangles or text', picker=True) ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red')) line, = ax1.plot(rand(100), 'o', picker=True, pickradius=5) # Pick the rectangle. ax2.bar(range(10), rand(10), picker=True) for label in ax2.get_xticklabels(): # Make the xtick labels pickable. label.set_picker(True) def onpick1(event): if isinstance(event.artist, Line2D): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]])) elif isinstance(event.artist, Rectangle): patch = event.artist print('onpick1 patch:', patch.get_path()) elif isinstance(event.artist, Text): text = event.artist print('onpick1 text:', text.get_text()) fig.canvas.mpl_connect('pick_event', onpick1) ``` -------------------------------- ### Get all figure numbers Source: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.get_fignums.html This example demonstrates how to use `matplotlib.pyplot.get_fignums()` to get a list of all currently open figure numbers. It first creates a few figures to ensure there are numbers to retrieve. ```APIDOC ## matplotlib.pyplot.get_fignums ### Description Return a list of existing figure numbers. ### Method ```python matplotlib.pyplot.get_fignums() ``` ### Parameters This function does not take any parameters. ### Returns - list: A list of integers, where each integer is a figure number. ### Example ```python import matplotlib.pyplot as plt # Create a few figures plt.figure(1) plt.figure(2) # Get all figure numbers fignums = plt.get_fignums() print(fignums) # Output: [1, 2] # Create another figure plt.figure() fignums = plt.get_fignums() print(fignums) # Output: [1, 2, 3] ``` ``` -------------------------------- ### FileMovieWriter.setup() Source: https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FileMovieWriter.html Sets up the writer for saving the movie file, specifying the figure, output file, and DPI. ```APIDOC ## FileMovieWriter.setup() ### Description Prepares the writer to begin saving the movie file. This method must be called before grabbing frames. ### Parameters * **fig** (`Figure`) - The matplotlib Figure object to capture frames from. * **outfile** (str) - The path to the output movie file. * **dpi** (float, default: `fig.dpi`) - The resolution of the output file in dots per inch. * **frame_prefix** (str, optional) - A prefix for temporary frame filenames. If None, frames are saved to a temporary directory. ``` -------------------------------- ### Get Matplotlib Version Source: https://matplotlib.org/stable/install/index.html Retrieve the version number of the currently installed Matplotlib package. ```python >>> import matplotlib >>> matplotlib.__version__ '0.98.0' ``` -------------------------------- ### Import Matplotlib and NumPy Source: https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html Imports necessary libraries for plotting and numerical operations. This is a common setup for Matplotlib examples. ```python import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors from matplotlib.patches import Rectangle ``` -------------------------------- ### Import Libraries and Setup Source: https://matplotlib.org/stable/_downloads/3521362dc0e73684626f9a6f0a9ec8a0/hist.ipynb Imports necessary libraries and sets up a random number generator for reproducible data generation. ```python import matplotlib.pyplot as plt import numpy as np from matplotlib import colors from matplotlib.ticker import PercentFormatter # Create a random number generator with a fixed seed for reproducibility rng = np.random.default_rng(19680801) ``` -------------------------------- ### Setup for Zorder Demo Source: https://matplotlib.org/stable/gallery/misc/zorder_demo.html Imports necessary libraries and generates sample data for plotting. ```python import matplotlib.pyplot as plt import numpy as np r = np.linspace(0.3, 1, 30) theta = np.linspace(0, 4*np.pi, 30) x = r * np.sin(theta) y = r * np.cos(theta) ``` -------------------------------- ### Show Locally Built Documentation Source: https://matplotlib.org/stable/devel/document.html Use the 'make show' command to open the locally built HTML documentation in your default web browser. ```bash make show ``` -------------------------------- ### Import Matplotlib Modules Source: https://matplotlib.org/stable/_downloads/210021ff118a667d0bea86dcb158be37/fancybox_demo.ipynb Imports necessary modules from Matplotlib for plotting and creating patches. This is a common setup for Matplotlib examples. ```python import inspect import matplotlib.pyplot as plt import matplotlib.patches as mpatch from matplotlib.patches import FancyBboxPatch import matplotlib.transforms as mtransforms ``` -------------------------------- ### Unit Definitions and Conversions Source: https://matplotlib.org/stable/gallery/units/basic_units.html Example setup for specific units like centimeters, inches, radians, and time units with conversion factors. ```python cm = BasicUnit('cm', 'centimeters') inch = BasicUnit('inch', 'inches') inch.add_conversion_factor(cm, 2.54) cm.add_conversion_factor(inch, 1/2.54) radians = BasicUnit('rad', 'radians') degrees = BasicUnit('deg', 'degrees') radians.add_conversion_factor(degrees, 180.0/np.pi) degrees.add_conversion_factor(radians, np.pi/180.0) secs = BasicUnit('s', 'seconds') hertz = BasicUnit('Hz', 'Hertz') minutes = BasicUnit('min', 'minutes') secs.add_conversion_fn(hertz, lambda x: 1./x) secs.add_conversion_factor(minutes, 1/60.0) ``` -------------------------------- ### Setup Qt Toolbar Source: https://matplotlib.org/stable/gallery/user_interfaces/mplcvd.html Sets up a Qt toolbar with a QToolButton that displays a QMenu. This is compatible with both Qt5 and Qt6. ```python def _setup_qt(tb): from matplotlib.backends.qt_compat import QtGui, QtWidgets menu = QtWidgets.QMenu() try: QActionGroup = QtGui.QActionGroup # Qt6 except AttributeError: QActionGroup = QtWidgets.QActionGroup # Qt5 group = QActionGroup(menu) group.triggered.connect(lambda action: _set_menu_entry(tb, action.text())) for name in _MENU_ENTRIES: action = menu.addAction(name) action.setCheckable(True) action.setActionGroup(group) action.setChecked(name == "None") actions = tb.actions() before = next( (action for action in actions if isinstance(tb.widgetForAction(action), QtWidgets.QLabel)), None) tb.insertSeparator(before) button = QtWidgets.QToolButton() # FIXME: _icon needs public API. button.setIcon(tb._icon(str(Path(__file__).parent / "images/eye.png"))) button.setText(_BUTTON_NAME) button.setToolTip(_BUTTON_HELP) button.setPopupMode(QtWidgets.QToolButton.ToolButtonPopupMode.InstantPopup) button.setMenu(menu) tb.insertWidget(before, button) ``` -------------------------------- ### Infinite Lines Example Source: https://matplotlib.org/stable/gallery/index.html Demonstrates the creation of infinite lines in a plot. No specific setup is required beyond standard Matplotlib imports. ```python import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.plot([0, 1], [0, 1], transform=ax.transAxes) ax.plot([0, 1], [1, 0], transform=ax.transAxes) plt.show() ``` -------------------------------- ### WebAggApplication.initialize Source: https://matplotlib.org/stable/api/backend_webagg_api.html Initializes the WebAggApplication. ```APIDOC ## WebAggApplication.initialize ### Description Initializes the WebAggApplication. ### Parameters #### Keyword Parameters - **url_prefix** (str, optional) - The URL prefix for the application. - **port** (int, optional) - The port to run the application on. - **address** (str, optional) - The address to bind the application to. ``` -------------------------------- ### matplotlib.testing.setup Source: https://matplotlib.org/stable/api/testing_api.html General setup function for Matplotlib testing. ```APIDOC ## matplotlib.testing.setup ### Description General setup function for Matplotlib testing. This may include environment variable configurations or other necessary preparations for running tests. ### Usage Typically called at the beginning of a test suite. ``` -------------------------------- ### Setup fake data for box plots Source: https://matplotlib.org/stable/_downloads/43dfdc3242d6e3f7d2a54971e771b799/boxplot.ipynb Initializes random lognormal data and labels for use in subsequent box plot examples. ```python import matplotlib.pyplot as plt import numpy as np # fake data np.random.seed(19680801) data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75) labels = list('ABCD') fs = 10 # fontsize ``` -------------------------------- ### AbstractMovieWriter.setup Source: https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.AbstractMovieWriter.html Abstract method to set up the movie writing process. It takes the figure object, output filename, and an optional DPI. ```APIDOC abstractmethod setup(_fig_ , _outfile_ , _dpi =None_)[source]# Setup for writing the movie file. Parameters: **fig**`Figure` The figure object that contains the information for frames. **outfile** str The filename of the resulting movie file. **dpi** float, default: `fig.dpi` The DPI (or resolution) for the file. This controls the size in pixels of the resulting movie file. ```