NumPy - Matplotlib
NumPy - Plotting with Matplotlib
Section titled “NumPy - Plotting with Matplotlib”Matplotlib is the most widely used data visualization library for Python. It provides a powerful and flexible platform for creating static, animated, and interactive plots. When used alongside NumPy, it offers a numerical and plotting environment similar to MATLAB, but within the open-source Python ecosystem.
Matplotlib integrates well with NumPy arrays, making it easy to plot data generated or manipulated using NumPy. It can also be embedded in various graphical user interface toolkits like Tkinter, PyQt, and wxPython.
The matplotlib.pyplot submodule provides a convenient interface for creating plots. By convention, it is imported as plt:
import matplotlib.pyplot as pltThe plt.plot() function is fundamental for creating 2D line plots. Let’s plot the simple linear equation y = 2x + 5.
Example: Basic Line Plot
Section titled “Example: Basic Line Plot”import numpy as npimport matplotlib.pyplot as plt
# Prepare data using NumPyx = np.arange(1, 11) # x values from 1 to 10y = 2 * x + 5 # Corresponding y values
# Create the plotplt.plot(x, y) # Plot y vs x
# Add labels and title for clarityplt.title("Simple Line Plot")plt.xlabel("X Axis Label")plt.ylabel("Y Axis Label")
# Display the plotplt.show()First, a NumPy array x is created using np.arange(). The corresponding y values are calculated using element-wise operations. plt.plot(x, y) generates the line plot. Functions like plt.title(), plt.xlabel(), and plt.ylabel() add descriptive elements. Finally, plt.show() displays the generated plot window.
Expected Output Description:
This code will display a window containing a plot. The plot shows a straight line rising from left to right, representing the linear relationship y = 2x + 5 for x values from 1 to 10. The axes are labeled “X Axis Label” and “Y Axis Label”, and the plot has the title “Simple Line Plot”.
You can customize the appearance of the plot by providing a format string to the plot() function. This string can specify color, marker style, and line style.
Common Marker Styles:
| Character | Description |
|---|---|
| ’.‘ | Point marker |
| ’o’ | Circle marker |
| ’s’ | Square marker |
| ’^‘ | Triangle up marker |
| ’*‘ | Star marker |
| ’+‘ | Plus marker |
| ’x’ | X marker |
| ’D’ | Diamond marker |
Common Line Styles:
| Character | Description |
|---|---|
| ’-‘ | Solid line style |
| ’—‘ | Dashed line style |
| ’-.‘ | Dash-dot line style |
| ’:‘ | Dotted line style |
Common Color Abbreviations:
| Character | Color |
|---|---|
| ’b’ | Blue |
| ’g’ | Green |
| ’r’ | Red |
| ’c’ | Cyan |
| ’m’ | Magenta |
| ’y’ | Yellow |
| ’k’ | Black |
| ’w’ | White |
For example, to plot blue circles instead of a line, use the format string 'ob' (o for circle marker, b for blue color).
Example: Plotting with Markers
Section titled “Example: Plotting with Markers”import numpy as npimport matplotlib.pyplot as plt
x = np.arange(1, 11)y = 2 * x + 5
plt.title("Plot with Markers")plt.xlabel("X Axis")plt.ylabel("Y Axis")
# Plot using blue ('b') circle ('o') markersplt.plot(x, y, 'ob')
plt.show()Expected Output Description:
This code will display a plot similar to the first example, but instead of a solid line, it shows individual blue circular markers at each (x, y) data point.
Sine Wave Plot
Section titled “Sine Wave Plot”A common example is plotting trigonometric functions like the sine wave.
Example: Plotting a Sine Curve
Section titled “Example: Plotting a Sine Curve”import numpy as npimport matplotlib.pyplot as plt
# Compute x and y coordinates for points on a sine curvex = np.arange(0, 3 * np.pi, 0.1) # x values from 0 to 3*pi with 0.1 stepy = np.sin(x) # Calculate sine of each x value
plt.title("Sine Wave")plt.xlabel("x (radians)")plt.ylabel("sin(x)")
# Plot the points using matplotlibplt.plot(x, y)plt.show()Expected Output Description:
This displays a plot window showing a smooth sine wave oscillating between -1 and 1 on the y-axis, over the range of x values from 0 to approximately 9.42 (3 * pi) on the x-axis.
subplot()
Section titled “subplot()”The plt.subplot() function allows you to arrange multiple plots within the same figure window (in a grid). You specify the number of rows, number of columns, and the index of the current plot.
Example: Plotting Sine and Cosine in Subplots
Section titled “Example: Plotting Sine and Cosine in Subplots”import numpy as npimport matplotlib.pyplot as plt
# Compute x and y coordinates for points on sine and cosine curvesx = np.arange(0, 3 * np.pi, 0.1)y_sin = np.sin(x)y_cos = np.cos(x)
# Create a figure and a set of subplots# plt.figure() # Optional: Creates a new figure
# Set up a subplot grid: 2 rows, 1 column. Activate the 1st subplot.plt.subplot(2, 1, 1)plt.plot(x, y_sin)plt.title('Sine')plt.ylabel('sin(x)')
# Activate the 2nd subplot.plt.subplot(2, 1, 2)plt.plot(x, y_cos)plt.title('Cosine')plt.xlabel('x (radians)')plt.ylabel('cos(x)')
# Adjust layout to prevent overlapping titles/labelsplt.tight_layout()
# Show the figure containing both subplots.plt.show()Expected Output Description:
This displays a figure window with two plots stacked vertically. The top plot shows the sine wave titled ‘Sine’, and the bottom plot shows the cosine wave titled ‘Cosine’. Both plots share the same x-axis range.
The plt.bar() function creates bar charts, useful for comparing categorical data.
Example: Simple Bar Chart
Section titled “Example: Simple Bar Chart”import matplotlib.pyplot as plt
# Data for the first set of barsx = [5, 8, 10]y = [12, 16, 6]
# Data for the second set of barsx2 = [6, 9, 11]y2 = [6, 15, 7]
# Create the bar chartplt.bar(x, y, align='center', label='Set 1')# Plot second set with different colorplt.bar(x2, y2, color='g', align='center', label='Set 2')
plt.title('Bar Graph Example')plt.ylabel('Y axis values')plt.xlabel('X axis categories/positions')plt.legend() # Display labels
plt.show()Expected Output Description:
This code displays a bar chart. It shows two sets of bars at different x-positions. The first set (at x=5, 8, 10) is blue by default, and the second set (at x=6, 9, 11) is green (‘g’). The heights of the bars correspond to the y-values. A legend distinguishes ‘Set 1’ and ‘Set 2’.