YouTip LogoYouTip

Matplotlib Ref Plot

* * Matplotlib Reference](#) `plot()` is the most core 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-length argument | Supports multiple calling methods: plot(y), plot(x, y), plot(x, y, 'fmt'), plot(x1, y1, 'fmt1', x2, y2, 'fmt2', ...) | | scalex / scaley | bool | Whether to automatically scale the x/y axis to fit the data, default is True | | data | Indexable object | If provided, string can be used as parameters to reference its data columns | | color or c | color | Line color, such as 'red', '#ff0000', 'tab:blue' | | linestyle or ls | str | Line style: '-' (solid), '--' (dashed), '-.' (dash-dot), ':' (dotted), '' (no line) | | linewidth or lw | float | Line width, default is about 1.5 | | marker | str | Data point marker: '.', 'o', 's', '^', '*', '+' (plus), '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, larger values are placed on top | > The fmt format string consists of three parts: `''`, for example, `'ro--'` means red, circle marker, dashed line. The order of each part can be arranged arbitrarily. ## 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 Only pass in y values, x automatically uses indices starting from 0. ## Instance import matplotlib.pyplot as plt 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 Strings Draw multiple curves on the same plot, using different colors, line styles, and markers. ## Instance import matplotlib.pyplot as plt 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 using a different format plt.plot(x, y1,'b-o', label='sin(x)')# Blue solid line + circle plt.plot(x, y2,'r--s', label='cos(x)')# Red dashed line + square plt.plot(x, y3,'g-.^', label='damped sin(x)')# Green dash-dot line + triangle 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 Styles Using Keyword Arguments Use keyword arguments to more finely control the appearance of lines. ## Instance import matplotlib.pyplot as plt 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 strings, 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 fill color markeredgecolor='black',# Marker edge color markeredgewidth=0.5,# Marker edge width alpha=0.8,# Overall transparency label='sin(x)') # Contrast: 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("tutorial: 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. ## Instance import matplotlib.pyplot as plt 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 Method) Using the object-oriented Axes interface is clearer in multi-subplot scenarios. ## Instance import matplotlib.pyplot as plt 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: Math functions 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() * * * ## Frequently Asked Questions ### Order of x and y in plot() The standard call is `plot(x, y)`, with x first and y last. If only one array is passed, such as `plot(y)`, x automatically takes `range(0, len(y))`. ### How to draw discontinuous line segments? For data containing NaN, plot() will automatically break the line at NaN, which can be used to draw segmented lines. ### Can fmt strings and keyword arguments be used at the same time? Yes, keyword arguments will override the corresponding settings in the fmt string. For example, in `plot(x, y, 'ro', color='blue')`, marker='o' comes from fmt, but color will be overridden to blue. [![Image 2: Matplotlib Reference](#) Matplotlib Reference](#)
← Matplotlib Ref ScatterMatplotlib Ref Legend β†’