Matplotlib plot() Function
Matplotlib Reference Documentation
plot()It is the most central function in Matplotlib, used to draw line charts.
It creates lines by connecting given x and y coordinate points, and supports customizing color, line style, marker, and line width.
Function Definition
pyplot Interface
matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
Axes Interface
Axes.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
Parameter Description
| Parameter | Type | Description |
|---|---|---|
| *args | Variable arguments | Supports multiple calling conventions: plot(y), plot(x, y), plot(x, y, 'fmt'), plot(x1, y1, 'fmt1', x2, y2, 'fmt2', ...) |
| scalex / scaley | bool | Whether to automatically scale x/y axes to fit the data, default is True |
| data | Indexable object | If provided, strings can be used as arguments to reference data columns in it. |
| color or c | color | Line color, e.g., 'red', '#ff0000', 'tab:blue' |
| linestyle or ls | str | Line style: '-' (solid), '--' (dashed), '-.' (dash-dot), ':' (dotted), '' (no line) |
| linewidth or lw | float | Line width, default approximately 1.5 |
| marker | str | Data point markers: '.', 'o', 's', '^', '*', '+' (plus sign), 'x', etc. |
| markersize or ms | float | Marker size |
| label | str | Legend label, used with legend() |
| alpha | float | Transparency, from 0 (fully transparent) to 1 (fully opaque) |
| zorder | float | Layer order, the larger the value, the higher it is drawn |
The fmt format string consists of three parts:
'[Color][Marker][Line Style]'such as'ro--'indicates red, circle marker, dashed line. The order of the parts is arbitrary.
Common Color Abbreviations
| Character | Color | Character | Color |
|---|---|---|---|
| 'b' | Blue | 'r' | Red |
| 'g' | Green | 'c' | Cyan |
| 'm' | Magenta | 'y' | Yellow |
| 'k' | Black | 'w' | White |
Usage Examples
Example 1: The Simplest Line Chart
If only y values are passed, x automatically uses indices starting from 0.
Example
import numpy as np
# Generate 50 data points between 0-10
x = np.linspace(0, 10, 50)
y = np.sin(x) # Sine function
# Simplest call: x, y
plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True, alpha=0.3)
plt.show()
Example 2: Multiple Curves + Format String
Draw multiple curves on the same plot, using different colors, line styles, and markers.
Example
import numpy as np
x = np.linspace(0, 10, 50)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.exp(-x / 3) # Damped sine
# Multiple curves, each with a different format
plt.plot(x, y1, 'b-o', label='sin(x)') # Blue solid line + circle markers
plt.plot(x, y2, 'r--s', label='cos(x)') # Red dashed line + square markers
plt.plot(x, y3, 'g-.^', label='damped sin(x)') # Green dash-dot line + triangle markers
plt.title('Multiple Lines with Different Styles')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Example 3: Customizing Style with Keyword Arguments
Use keyword arguments for finer control over line appearance.
Example
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
# Use keyword arguments instead of format string, more readable
ax.plot(x, np.sin(x),
color='steelblue', # Color name
linestyle='-', # Solid line
linewidth=2.5, # Line width
marker='o', # Circle marker
markersize=4, # Marker size
markerfacecolor='red', # Marker face color
markeredgecolor='black', # Marker edge color
markeredgewidth=0.5, # Marker edge width
alpha=0.8, # Overall transparency
label='sin(x)')
# Comparison: dashed line without markers
ax.plot(x, np.cos(x),
color='#ff6600', # Hexadecimal color
linestyle='--',
linewidth=2,
label='cos(x)')
ax.set_title('Customized Line Styles', fontsize=14)
ax.set_xlabel('x (radians)')
ax.set_ylabel('Amplitude')
ax.legend(loc='upper right')
ax.grid(True, alpha=0.2)
plt.show()
print("example: customized plot displayed")
Example 4: Using the data Parameter (DataFrame Support)
When the data is a dict or pandas DataFrame, string column names can be used.
Example
import numpy as np
# Organize data as a dictionary
data = {
'time': np.arange(0, 10, 0.5),
'voltage': np.sin(np.arange(0, 10, 0.5)) * 5 + 10,
'current': np.cos(np.arange(0, 10, 0.5)) * 2 + 5,
}
fig, ax = plt.subplots(layout='constrained')
# Reference data via the data parameter + string column names
ax.plot('time', 'voltage', 'b-', data=data, label='Voltage (V)')
ax.plot('time', 'current', 'r--', data=data, label='Current (A)')
ax.set_title('Using data Parameter with Column Names')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Value')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
Example 5: Calling on an Axes Object (Recommended Approach)
Using the object-oriented Axes interface is clearer in multi-subplot scenarios.
Example
import numpy as np
x = np.linspace(0, 10, 100)
# Create two side-by-side subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# Left subplot: mathematical function
ax1.plot(x, np.sin(x), label='sin(x)')
ax1.plot(x, np.cos(x), label='cos(x)')
ax1.set_title('Math Functions')
ax1.legend()
ax1.grid(True, alpha=0.3)
# Right subplot: data trend
data = np.random.randn(100).cumsum() # Random walk
ax2.plot(data, color='teal', linewidth=1.5)
ax2.set_title('Random Walk (cumulative sum)')
ax2.set_xlabel('Step')
ax2.set_ylabel('Position')
ax2.grid(True, alpha=0.3)
plt.show()
FAQ
Order of x and y in plot()
The standard call isplot(x, y), x comes first, y comes after.
If only one array is passed, e.g.plot(y), then x is automatically taken asrange(0, len(y))。
How to Draw Discontinuous Line Segments?
For data containing NaN, plot() automatically breaks the line at NaN, which can be used to draw segmented lines.
Can the fmt String and Keyword Arguments Be Used Together?
Yes, keyword arguments override the corresponding settings in the fmt string. For exampleplot(x, y, 'ro', color='blue')Here, marker='o' comes from fmt, but color will be overridden to blue.
Other Extensions