Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib plot() Function

Matplotlib plot() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

plot() is the most core function in Matplotlib, used to draw line plots.

It creates lines by connecting the given x and y coordinate points, supporting custom colors, line styles, markers, and line widths.

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

Parameters Type Description
*args Variable arguments (varargs) Supports multiple calling styles: 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 axes to fit the data, default True
data Indexable object If provided, string arguments can be used to reference data columns within it
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 about 1.5
marker str Data point markers: '.', '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:'[颜色][标记][线型]', such as 'ro--' represents red color, circle marker, dashed line. The order of the parts can be arbitrary.

Common color abbreviations

Character Color Character Color
'b' Blue: blue 'r' Red: red
'g' Green: green 'c' Cyan: cyan
'm' Magenta: magenta 'y' Yellow: yellow
'k' Black: black 'w' White: white

Usage examples

Example 1: The simplest line plot

Pass only y values; x automatically uses indices starting from 0.

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Generate 50 data points between 0 and 10

x

=

np.

linspace

(

0

,

10

,

50

)

y

=

np.

sin

(

x

)

 

Sine function

The 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

Plot multiple curves on the same chart using different colors, line styles, and markers.

Example

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

)

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 marker

plt.

plot

(

x

,

y2

,

'r--s'

,

label

=

'cos(x)'

)

         

Red dashed line + square marker

plt.

plot

(

x

,

y3

,

'g-.^'

,

label

=

'damped sin(x)'

)

 

Green dash-dot line + triangle marker

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 with keyword arguments

Use keyword arguments for finer control over the line appearance.

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

0

,

2

pi

,

100

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

4

)

,

layout

=

'constrained'

)

Using keyword arguments instead of format strings is 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 colors

        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

(

"runoob: 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

matplotlib.

pyplot

as

plt

import

numpy

as

np

Organize the data into 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

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: 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

(

)


Common questions

The order of x and y in plot()

The standard call is plot(x, y), with x first and y second.

If only one array is passed, such as plot(y), then x automatically takes range(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 fmt strings and keyword arguments be used together?

Yes, keyword arguments override the corresponding settings in the fmt string. For example plot(x, y, 'ro', color='blue') , marker='o' comes from fmt, but color is overridden to blue.

Matplotlib Reference Documentation Matplotlib Reference Documentation