Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 57 ยท Core Chart Types

Broken Bars, matshow, spy, tricontour and triplot

Learn five specialist Matplotlib charts: broken_barh timelines, matshow and spy for matrices, and tricontour, tricontourf and triplot for scattered points.

Bar charts, histograms and heatmaps solve most problems. Then a different question arrives: when was each machine busy? Where are the non-zero entries of this huge matrix? What does the field look like between 200 sensors scattered over a map? Matplotlib has a small tool for each. They are less famous, but each one replaces a lot of hand-made code.

This lesson covers five of them: broken_barh for timelines made of separate stretches, matshow for showing a matrix as a table of colours, spy for its pattern of non-zero values, and tricontour / tricontourf / triplot for data that does not sit on a regular grid. You should know basic bar charts and heatmaps first.

broken_barh: timelines and Gantt-style charts

An ordinary bar runs from zero to a value. A broken horizontal bar is a row of rectangles that may have gaps between them. ax.broken_barh(xranges, yrange) takes a list of (start, width) pairs along x, and one (bottom, height) pair along y. Each call draws one row, so a schedule with five machines is five calls.

That makes it ideal for when was something active: machine usage, meeting rooms, project phases, availability, the on and off states of a signal.

Python A machine schedule with broken_barh

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 y range (row * 10 + 2, 6) means "start at y = row*10+2 and be 6 units tall", so each machine gets its own lane with a gap between lanes. The y axis is just numbers, so we put the machine names on the ticks with set_yticks(positions, labels=...). For real dates, give x positions as Matplotlib date numbers (matplotlib.dates.date2num) or use ax.xaxis_date(), as in Dates and Time Series.

matshow: a matrix as a table of colours

ax.matshow(matrix) is imshow with defaults chosen for matrices: the x-axis ticks and labels sit at the top, the origin is the top left like a printed matrix, and the aspect ratio is equal so cells are square. It is the natural tool for a correlation matrix, a confusion matrix or any small table where you want to read cells like rows and columns.

Python A confusion matrix with matshow

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.

np.ndenumerate walks every cell, giving the (row, column) index and the value, so each number can be printed in its cell. The text colour switches to white on dark cells. With imshow you would get the same picture with the x axis at the bottom; matshow simply saves you the ax.xaxis.tick_top() call. Remember ax.set_xticks(positions, labels=...) to show names instead of indices.

spy: the pattern of non-zero values

Large matrices in science and machine learning are often sparse: nearly all entries are zero. What matters is where the non-zeros are, because the pattern reveals structure (bands, blocks, symmetry). ax.spy(matrix) draws a dot (or a tiny rectangle) wherever the matrix has a non-zero value, and nothing elsewhere. It also accepts SciPy sparse matrices without converting them to a dense array.

Python Spy on three sparse patterns

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 three shapes tell three stories: a band around the diagonal is typical for neighbour-to-neighbour interactions (a chain or a grid), blocks mean independent groups, and scattered dots have no structure. precision=0.1 makes spy treat values with an absolute value at or below 0.1 as zero, which is handy for dense matrices with tiny noise. markersize controls the size of the dots (set it to 0 to draw one pixel per cell for very large matrices).

tricontour, tricontourf and triplot: scattered points

The contour functions you know need a regular grid: X and Y from meshgrid. Real measurements rarely sit on a grid: weather stations, soil samples, wells, sensors. The triangulation family handles such points directly. Matplotlib builds a Delaunay triangulation (a network of triangles joining the nearest points) and then draws on it.

  • ax.triplot(x, y) draws just the triangle mesh, so you can see how the points are connected.
  • ax.tricontour(x, y, z, levels) draws contour lines of z.
  • ax.tricontourf(x, y, z, levels) draws filled contour bands.
Python Scattered sensors: mesh, lines and filled contours

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.

Matplotlib triangulates the points for you, but you can also build the triangulation once with matplotlib.tri.Triangulation(x, y) and pass it to all three functions: ax.tricontourf(tri, z). That is useful when you plot several variables over the same points, because the triangulation is computed only once.

Warning: The triangulation joins the outermost points even where you have no data, so the corners of an irregular region can show invented values. Draw the sensor positions on top (as above) and be careful about reading values far from any point. If the data is almost on a grid, a normal contourf after interpolation may be the better choice.

Which one do you need?

Five specialist charts

broken_barh Busy and idle stretches
matshow A matrix as coloured cells
spy Where are the non-zeros?
tri* Contours from scattered points

Pick by the shape of your data.

1 / 2

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do the arguments of ax.broken_barh([(1, 3), (6, 2)], (0, 5)) mean?

    Each pair is (start, width) along x, so the bars span 1 to 4 and 6 to 8. The second argument is (bottom, height) along y.
  2. 2. How does matshow differ from imshow for a matrix?

    matshow is imshow with matrix-friendly defaults: ticks at the top and square cells. It accepts the same cmap and norm arguments.
  3. 3. What does ax.spy(m) display?

    spy plots the sparsity pattern: marks where the entries are non-zero. It is used to see bands, blocks and symmetry in large matrices.
  4. 4. Why use tricontourf instead of contourf?

    contourf needs 2D grids (from meshgrid). tricontourf triangulates scattered (x, y, z) points, so irregular measurements can be drawn directly.
  5. 5. What should you be careful about with triangulated contour plots?

    The Delaunay triangulation joins nearby points, even across empty areas. Plot the sample positions and do not read values far from any point.

Summary

  • broken_barh([(start, width), ...], (bottom, height)) draws one lane of separate bars: schedules, availability and phases.
  • matshow is imshow tuned for matrices (ticks on top, square cells); add numbers with ax.text and np.ndenumerate.
  • spy marks non-zero entries so the structure of a sparse matrix (bands, blocks, noise) is visible; it accepts SciPy sparse matrices.
  • triplot, tricontour and tricontourf triangulate scattered points; share one matplotlib.tri.Triangulation between several plots.
  • Show the sample points on a triangulated plot, and do not trust areas without data.

Next: Error Bars and Uncertainty shows how to draw uncertainty.