Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 45 ยท Plotting and Visualization

Bar, Scatter, Histogram and Images

Choose the right chart in MATLAB and Octave: bar, scatter, histogram, why to avoid pie, imagesc and colormap, semilogx and loglog axes, and errorbar, with matplotlib stand-ins.

A line plot is perfect for a function of one variable, but data comes in many shapes. Categories call for bars, two measurements per item call for a scatter plot, a pile of samples calls for a histogram, and a grid of numbers calls for an image. Choosing the chart that fits the question is half of good visualization.

The MATLAB and Octave commands are shown read-only, and each has a matplotlib TryIt drawing the same chart. You should already know the basics from 2-D Plots. Where Octave differs, it is noted.

Which chart for which question?

bar Compare a value across categories.
scatter Relationship between two variables.
histogram How are values distributed?
imagesc Show a matrix as colors.
1 / 2

Bar charts

bar(values) draws one bar per element; bar(x, values) positions the bars at x. Matrices make grouped bars, one group per row. Label categories with xticklabels, or set(gca, 'XTickLabel', ...) in older code.

MATLAB
sales = [12 19 7 15];
bar(sales)
xticklabels({'Q1', 'Q2', 'Q3', 'Q4'})
ylabel('Units sold')
title('Sales by quarter')

barh(sales)          % horizontal bars, good for long labels

Always start the value axis of a bar chart at zero: bar length is read as quantity, and a truncated axis exaggerates differences.

Python A bar chart with category 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.

Scatter plots

scatter(x, y) draws one marker per point and can encode more: a size vector, a color vector, and 'filled' for solid dots.

MATLAB
rng(1)                              % reproducible random numbers
x = randn(1, 80);
y = 0.8*x + 0.4*randn(1, 80);
scatter(x, y, 30, x, 'filled')      % color by x
colorbar
xlabel('x'); ylabel('y')

For a simple scatter, plot(x, y, 'o') is faster to draw with thousands of points. Add a trend with polyfit and plot, which Polynomials and Curve Fitting covers. Random numbers differ between MATLAB and Octave even with the same seed, so the picture will not match pixel for pixel.

Python Scatter with color and a trend line

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.

Histograms

A histogram splits the range of the data into bins and counts how many values fall in each.

MATLAB
data = randn(1, 1000);
histogram(data)                     % MATLAB: automatic bin choice
histogram(data, 20)                 % 20 bins
histogram(data, 'Normalization', 'pdf')   % area of 1

[counts, centers] = hist(data, 20); % Octave (and old MATLAB)
bar(centers, counts)

histogram is the modern MATLAB function. Octave has traditionally used hist, which returns counts and bin centers you can pass to bar. Too few bins hide structure, too many make noise; try a few values. The statistics behind this are developed in Statistics and Random Numbers.

A word about pie charts

pie(values) exists, and people love it, but it is a weak choice: humans judge angles and areas poorly, so slices of similar size are hard to rank, and a pie with more than three or four slices becomes unreadable. A sorted bar chart nearly always tells the same story more clearly. If you need one, keep slices few, label them directly, and make sure the parts add up to a whole.

Matrices as images: imagesc and colormap

imagesc(M) scales the values of a matrix to a range of colors; colormap picks the palette and colorbar shows the scale. This is the standard way to view a matrix, a correlation table or a 2-D field.

MATLAB
[X, Y] = meshgrid(linspace(-3, 3, 120));
Z = exp(-(X.^2 + Y.^2)) .* cos(3*X);
imagesc(Z)
colormap(parula)       % Octave: viridis or jet
colorbar
axis image             % square pixels
set(gca, 'YDir', 'normal')   % row 1 at the bottom, like a graph

Without the YDir line, row 1 of the matrix appears at the top, because imagesc treats the matrix like a picture. Prefer perceptually even palettes such as parula or viridis over jet, whose bright bands create fake features. imshow is for actual images with a fixed 0 to 255 or 0 to 1 range (see Image Processing Basics); imagesc rescales to the data.

Python A matrix shown as colors

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.

Logarithmic axes

When data spans orders of magnitude, a linear axis crushes the small values. Logarithmic axes spread them out:

  • semilogx(x, y) log scale on x;
  • semilogy(x, y) log scale on y, so an exponential y = a*exp(k*x) becomes a straight line;
  • loglog(x, y) both axes, so a power law y = a*x^p becomes a straight line with slope p.
MATLAB
x = logspace(0, 3, 50);                % 1 to 1000
loglog(x, 2*x.^1.5, 'b-')              % straight line, slope 1.5
grid on

Log axes cannot show zero or negative values. Gridlines on log plots (grid on) are valuable for reading values.

Error bars

errorbar(x, y, err) draws a point at each y with a vertical bar of length err above and below. Use it whenever each number is an average or an estimate with uncertainty.

MATLAB
x = 1:5;
y = [2.1 3.9 6.2 7.8 10.1];
err = [0.3 0.4 0.3 0.5 0.4];
errorbar(x, y, err, 'o-')
Python Error bars and a log-log power law

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which chart suits comparing one value across a few categories?

    Bar charts encode values as lengths from a common baseline, which is easy to compare across categories.
  2. 2. A power law y = a*x^p appears as a straight line on which plot?

    Taking logs of both sides gives log y = log a + p log x, a line with slope p. loglog shows exactly that.
  3. 3. Why does imagesc(M) often show the matrix upside down compared with a graph?

    Matrices display like pictures with row 1 at the top. set(gca,'YDir','normal') flips it to graph-style orientation.
  4. 4. What is a main weakness of pie charts?

    A sorted bar chart nearly always makes comparisons easier because length along a common baseline is read accurately.
  5. 5. What does errorbar(x, y, err) draw?

    Each point gets a bar showing its uncertainty, so readers can judge whether differences are meaningful.

Summary

  • Choose by question: bar for categories, scatter for relationships, histogram (Octave: hist) for distributions, imagesc for matrices.
  • Start bar axes at zero; consider a sorted bar chart instead of a pie.
  • scatter can encode size and color; add colorbar to explain color.
  • imagesc plus colormap and colorbar shows matrix values; remember row 1 is at the top unless you set YDir.
  • semilogx, semilogy and loglog straighten exponentials and power laws.
  • errorbar communicates uncertainty; matplotlib stand-ins draw the same charts.

Next, go three-dimensional with 3-D Plots, Surfaces and Contours.