Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 57 ยท Line Plots and Basic Styling

Line Plots in Depth

Go beyond one line: plot several series, functions and NumPy data, break lines with NaN, draw step plots, shade with fill_between and use dates on x.

The line plot is the workhorse of Matplotlib: a sequence of (x, y) points joined by straight segments. It suits anything that changes along a continuous axis, such as time, distance or a parameter. You have drawn simple ones in Your First Plot. This lesson covers the situations real data throws at you: several series, mathematical functions, missing values, step-like data, shaded regions and dates.

All examples use the fig, ax = plt.subplots() pattern from pyplot vs the Object-Oriented API.

Several lines on one Axes

Call ax.plot once per series. Matplotlib cycles through its default colors, and each call returns a list of Line2D objects you can keep. You can also pass several x-y pairs in one call, but separate calls with a label= read better.

Python Several series with labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep the number of lines small. More than five or six lines on one chart becomes a tangle; use multiple subplots instead.

Plotting functions

To draw a function, sample it at many x values and plot the arrays. np.linspace(a, b, n) includes both endpoints, and the number of points controls smoothness.

Python A function and its slope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With 401 points the curve is smooth. Because the sample includes exactly x = 0, the naive sin(x) / x produces one NaN (a gap in the line, as the next section explains), while np.sinc returns the correct limit of 1 there. Sampling functions at awkward points is a common source of unexpected gaps.

Gaps: NaN breaks the line

A NaN (not a number) is Matplotlib's way of saying "no data here". The line is not drawn through it; it breaks. This is the right behavior for missing readings, because connecting across a gap would invent data.

Python Missing values leave gaps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the choice: the solid line honestly breaks, and the dotted gray line is a clearly marked guess. More on handling NaN in Missing Data. With pandas, missing values behave the same way.

Line plot variations

Default Straight segments between points.
Step Holds the value until the next change.
NaN gaps Missing data breaks the line.
fill_between Shade the area or a band.

Same data, different message. Pick on purpose.

1 / 2

Step plots

Some quantities do not slide between values; they jump and then stay the same: a price list, a stock level, a thermostat setting. A straight diagonal between the points would claim values that never existed. Use ax.step, or drawstyle="steps-post" in plot.

The where argument says when the jump happens: "post" holds the value after each x (the value changes at the next x), "pre" holds it before, and "mid" jumps halfway between.

Python Line vs step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Shading with fill_between

ax.fill_between(x, y1, y2) fills the area between two curves (y2 defaults to 0). Use it to show a band, such as a range of plausible values, or to emphasize the area under a curve. Set alpha below 1 so lines show through.

Python Area and band

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The where= argument takes a boolean array, so you can shade only where a condition holds. Uncertainty bands get their own treatment in Error Bars and Uncertainty.

Dates on the x axis

Pass Python datetime objects or NumPy datetime64 values as x, and Matplotlib turns them into a date axis with sensible ticks. Long labels often overlap, so call fig.autofmt_xdate() to rotate them.

Python A date axis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fine control of date ticks (months, weeks, custom formats) is in Dates and Time Series Charts.

Transform the data before you plot

When values span orders of magnitude, a line plot of raw values squeezes all the detail into one corner. You can often plot the logarithm of the data instead of the data. Taking np.log10 first changes the data; setting a log scale (ax.set_yscale("log")) leaves the data alone and changes how the axis draws it, with tick labels in original units. The second is usually clearer for readers, and is covered in Limits, Scales and Aspect.

Python Raw, log10 and log scale

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On the right the exponential growth is a straight line, and the tick labels still show real counts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to a line plot at a NaN value in y?

    NaN means no data, so the line is broken and no segment is drawn across the gap.
  2. 2. A thermostat setting jumps from 16 to 21 at hour 8 and then stays there. Which call best represents it?

    A step plot holds each value until the next change, which matches quantities that jump instead of sliding.
  3. 3. What does ax.fill_between(x, lower, upper, alpha=0.2) draw?

    fill_between shades the region between two y curves; a low alpha keeps lines underneath visible.
  4. 4. What is the difference between np.log10(y) and ax.set_yscale('log')?

    Plotting log10 data labels the axis with log values. A log scale keeps the original data and shows real values on logarithmically spaced ticks.
  5. 5. Which call helps date labels on the x axis avoid overlapping?

    autofmt_xdate rotates and right-aligns date tick labels so they do not collide.

Summary

  • Call ax.plot once per series, give each a label, and keep the line count small.
  • Plot functions by sampling them with np.linspace; use enough points for a smooth curve.
  • NaN breaks a line; interpolate only when you mark the result as a guess.
  • Use ax.step for quantities that jump; use fill_between for bands and conditional shading.
  • Date and datetime64 values give a date axis; fig.autofmt_xdate() tidies the labels.
  • Prefer a log scale on the axis to hand-logging the data when the range spans orders of magnitude.

Next, make your lines look the way you want in Colors, Line Styles and Markers.