### Introduction to Matplotlib Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It's widely used for data analysis and scientific computing. **Key Components:** - `Figure`: The top-level container for all plot elements. - `Axes`: The actual plot area where data is plotted. A Figure can have multiple Axes. - `Artist`: Everything visible on the figure (titles, labels, lines, images etc.). ### Basic Imports & Setup Most common way to import and set up Matplotlib: ```python import matplotlib.pyplot as plt import numpy as np ``` **Interactive Mode:** `plt.ion()` - Turn interactive mode on. `plt.ioff()` - Turn interactive mode off. `plt.show()` - Display the figure (blocks execution in non-interactive mode). `plt.close()` - Close current figure. `plt.close('all')` - Close all figures. ### Figure and Axes Creation **1. Default Plot:** ```python plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show() ``` **2. Explicit Figure & Axes:** ```python fig = plt.figure() # An empty figure with no axes ax = fig.add_subplot(111) # A 1x1 grid, first subplot ax.plot([1, 2, 3, 4]) plt.show() ``` **3. Recommended Way (Subplots):** ```python fig, ax = plt.subplots() # Creates a figure and a single axes ax.plot([1, 2, 3, 4]) plt.show() ``` **4. Multiple Subplots:** ```python fig, axes = plt.subplots(nrows=2, ncols=2) # 2x2 grid of axes axes[0,0].plot(...) # Access specific axes plt.tight_layout() # Adjust subplot params for a tight layout plt.show() ``` - `plt.figure(figsize=(width, height), dpi=dots_per_inch)`: Control figure size and resolution. ### Line Plots (`plt.plot()`) The most basic plot type. **Syntax:** `ax.plot(x, y, [fmt], **kwargs)` - `x, y`: Data points. If `x` is omitted, `y` values are plotted against their index. - `fmt`: Optional format string (e.g., `'ro-'` for red circles connected by solid lines). **Examples:** ```python x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) ax.plot(x, y, label='sin(x)', color='blue', linestyle='--', linewidth=2) ax.plot(x, np.cos(x), 'g:^', label='cos(x)') # Green, dotted, triangle markers ``` **Format String (`fmt`):** | Color | Marker | Line Style | |-------|--------|------------| | `b` blue | `.` point | `-` solid | | `g` green | `o` circle | `--` dashed | | `r` red | `v` triangle_down | `:` dotted | | `c` cyan | `s` square | `-.` dash-dot | | `m` magenta | `P` plus (filled) | (none) no line | | `y` yellow | `*` star | | | `k` black | `x` x | | | `w` white | `D` diamond | | ### Scatter Plots (`plt.scatter()`) Used to display values for two variables for a set of data. **Syntax:** `ax.scatter(x, y, s=None, c=None, marker=None, alpha=None, **kwargs)` - `s`: Size of markers (scalar or array). - `c`: Color of markers (color string, sequence of colors, or array for colormap). - `marker`: Marker style. - `alpha`: Transparency (0 to 1). **Example:** ```python np.random.seed(0) x = np.random.rand(50) y = np.random.rand(50) colors = np.random.rand(50) sizes = 1000 * np.random.rand(50) ax.scatter(x, y, s=sizes, c=colors, alpha=0.7, cmap='viridis') ``` ### Bar Plots (`plt.bar()`, `plt.barh()`) Used for categorical data. **Syntax:** - `ax.bar(x, height, width=0.8, bottom=None, align='center', **kwargs)` - `ax.barh(y, width, height=0.8, left=None, align='center', **kwargs)` **Example (Vertical Bar):** ```python categories = ['A', 'B', 'C', 'D'] values = [23, 45, 56, 12] ax.bar(categories, values, color=['skyblue', 'lightcoral', 'lightgreen', 'gold']) ``` **Example (Horizontal Bar):** ```python ax.barh(categories, values, color='teal') ``` ### Histograms (`plt.hist()`) Display the distribution of a single variable. **Syntax:** `ax.hist(x, bins=10, range=None, density=False, cumulative=False, **kwargs)` - `x`: Data (array). - `bins`: Number of bins (int) or bin edges (sequence). - `density`: If True, normalize to form a probability density. - `cumulative`: If True, compute a cumulative histogram. **Example:** ```python data = np.random.randn(1000) ax.hist(data, bins=30, edgecolor='black', alpha=0.7) ``` ### Box Plots (`plt.boxplot()`) Show distribution of numerical data through quartiles. **Syntax:** `ax.boxplot(x, notch=False, vert=True, patch_artist=False, **kwargs)` - `x`: Data (array or sequence of arrays). - `notch`: If True, produce a notched box plot. - `vert`: If True, vertical boxes. If False, horizontal. **Example:** ```python data1 = np.random.normal(0, 1, 100) data2 = np.random.normal(1, 1.5, 100) ax.boxplot([data1, data2], labels=['Group 1', 'Group 2'], patch_artist=True) ``` ### Pie Charts (`plt.pie()`) Represent proportions of a whole. **Syntax:** `ax.pie(x, labels=None, autopct='%1.1f%%', explode=None, startangle=0, **kwargs)` - `x`: Array of wedge sizes. - `labels`: Sequence of strings for the labels. - `autopct`: String or function for formatting percentage labels. - `explode`: Sequence of floats to "explode" wedges. **Example:** ```python sizes = [15, 30, 45, 10] labels = ['Frogs', 'Hogs', 'Dogs', 'Logs'] explode = (0, 0.1, 0, 0) # Only "explode" the 2nd slice (Hogs) ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. ``` ### Figure Properties - `fig.suptitle('Figure Title')`: Set a title for the entire figure. - `fig.set_size_inches(width, height)`: Set figure size in inches. - `fig.savefig('my_plot.png', dpi=300, bbox_inches='tight')`: Save the figure. ### Axes Properties and Customization **Titles & Labels:** ```python ax.set_title('My Plot Title') ax.set_xlabel('X-axis Label') ax.set_ylabel('Y-axis Label') ``` **Limits:** ```python ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ``` **Ticks:** ```python ax.set_xticks([0, 1, 2, 3]) # Set specific tick locations ax.set_xticklabels(['A', 'B', 'C', 'D']) # Set custom tick labels ax.tick_params(axis='x', rotation=45) # Rotate x-axis labels ``` **Legend:** ```python ax.legend(loc='best') # 'best', 'upper left', 'center right', etc. ``` **Grid:** ```python ax.grid(True, linestyle='--', alpha=0.6) ``` **Text & Annotations:** ```python ax.text(x_coord, y_coord, 'Some Text', fontsize=12, color='red') ax.annotate('Peak!', xy=(x_peak, y_peak), xytext=(x_text, y_text), arrowprops=dict(facecolor='black', shrink=0.05)) ``` ### Multiple Plots on One Figure **1. `plt.subplots()`:** ```python fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) # 1 row, 2 columns ax1.plot(x, y) ax2.plot(y, x) plt.suptitle('Two Subplots Side-by-Side') plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout to make space for suptitle plt.show() ``` **2. `fig.add_subplot()`:** ```python fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_subplot(2, 1, 1) # 2 rows, 1 column, first plot ax2 = fig.add_subplot(2, 1, 2) # 2 rows, 1 column, second plot ax1.plot(x, y) ax2.scatter(x, y) plt.show() ``` **3. `plt.axes()` (Arbitrary Placement):** ```python fig = plt.figure() ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # [left, bottom, width, height] in figure coordinates ax2 = fig.add_axes([0.6, 0.6, 0.2, 0.2]) # Inset plot ax1.plot(x, y) ax2.plot(y, x, color='red') plt.show() ``` ### Colormaps Used for visualizing a scalar value in 2D or for scatter plots. **Setting Colormap:** - `ax.imshow(data, cmap='viridis')` - `ax.scatter(..., c=values, cmap='plasma')` **Common Colormaps:** - **Perceptually Uniform:** `viridis`, `plasma`, `inferno`, `magma`, `cividis` - **Diverging:** `RdBu`, `PuOr`, `bwr` - **Sequential:** `Blues`, `Greens`, `Reds`, `gray` **Colorbar:** ```python im = ax.imshow(np.random.rand(10, 10), cmap='viridis') fig.colorbar(im, ax=ax, label='Intensity') ``` ### 3D Plots (mplot3d) Requires importing `Axes3D` from `mpl_toolkits.mplot3d`. ```python from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 3D Scatter Plot ax.scatter(x_data, y_data, z_data, c='r', marker='o') # 3D Line Plot ax.plot(x_data, y_data, z_data, color='blue') # Surface Plot X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) ax.plot_surface(X, Y, Z, cmap='viridis') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') plt.show() ``` ### Styling and Themes **Stylesheets:** ```python plt.style.use('ggplot') # Apply 'ggplot' style # Other styles: 'seaborn-v0_8', 'dark_background', 'bmh', 'fivethirtyeight' # plt.style.available to see all ``` **Customizing RC Params:** Modify default settings globally. ```python plt.rcParams['lines.linewidth'] = 2 plt.rcParams['font.size'] = 12 plt.rcParams['figure.figsize'] = (10, 6) ``` ### Saving Plots ```python fig.savefig('my_plot.png', dpi=300, bbox_inches='tight', transparent=False) # Formats: png, pdf, svg, eps, jpg # dpi: Dots per inch (resolution) # bbox_inches='tight': Try to make sure all plot elements fit in the saved figure. # transparent=True: Make background transparent. ``` **Vector vs. Raster Formats:** - **Raster (PNG, JPG):** Good for web, fixed resolution. - **Vector (PDF, SVG, EPS):** Scalable without pixelation, good for print and reports.