Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 64 ยท Visualisation

Charts for Analysis

Use charts to answer questions about data. Draw distributions, grouped bars, rolling-mean trends, scatter plots with trend lines and correlation heatmaps.

Knowing how to call df.plot is the easy part. The skill is choosing the chart that answers your question and making it readable. A good analysis chart has one clear message, labels a stranger can understand and no decoration that gets in the way.

This lesson builds five analysis charts on generated data: a distribution, a comparison between groups, a trend with a smoothed line, a relationship with a trend line and a correlation heatmap. It assumes you know the basics from Plotting with pandas. Every example uses a fixed random seed so you get the same picture each time.

Start with the question

Pick the chart from the question, not the other way round.

flowchart TD
    Q["What do you want to show?"] --> A["How values are spread"]
    Q --> B["Compare groups"]
    Q --> C["Change over time"]
    Q --> D["Two numbers together"]
    Q --> E["Many numbers together"]
    A --> A1["Histogram or box plot"]
    B --> B1["Bar chart, sorted"]
    C --> C1["Line chart"]
    D --> D1["Scatter plot"]
    E --> E1["Correlation heatmap"]

A quick decision guide: the question on the left decides the chart on the right.

Distributions: histograms with reference lines

A histogram answers "what is typical, and how much do values vary?". Adding the mean and the median as vertical lines tells the reader at once whether the data is symmetric: for skewed data the two lines drift apart.

Python A skewed distribution with mean and median

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 long tail on the right pulls the mean above the median. When you see this shape, report the median as the "typical" value and mention the tail. Bins matter: bins=40 shows the shape clearly; bins=5 would hide it.

Comparing groups with bars

To compare categories, summarise first and plot second. groupby() or pivot_table() produces a small table, and plot.bar() draws it. Two habits make bar charts readable: sort the bars (unless the categories have a natural order), and start the value axis at zero.

Python Grouped bars from a pivot table

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 regions are ordered by total revenue, so the eye reads the ranking from left to right. The legend has a title, and the empty x label is removed because the region names already explain the axis. When there are many categories or long names, switch to barh() so the labels stay horizontal.

Daily data is noisy. A rolling mean averages each point with its neighbours and shows the direction. Plot the raw values faintly and the smoothed line boldly, so you see both the noise and the signal.

Python Daily values and a 7-day rolling mean

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 window of 7 matches the weekly cycle, so the weekend dip cancels out. The first and last three values of the rolling mean are NaN because center=True needs three neighbours on each side; dropna() skips them in the printout, and matplotlib leaves gaps there. fig.autofmt_xdate() rotates the date labels so they do not overlap. Rolling windows are covered in depth in Rolling, Expanding and EWM.

Relationships: scatter with a trend line

A scatter plot shows how two numbers move together. A fitted line makes the direction and strength easier to judge. NumPy's polyfit() fits a straight line in one call.

Python Scatter plot with a fitted 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.

The slope says that each extra thousand in ad spend goes with roughly 4.5 more thousand in sales (slope 4.55) in this made-up data. Be careful with words: a trend line shows association, not cause. Something else, such as the season, could drive both numbers.

Many relationships: a correlation heatmap

With a dozen numeric columns you cannot look at every scatter plot. df.corr() computes the correlation between every pair, from -1 (move in opposite directions) through 0 (no linear relationship) to +1 (move together). Drawn as a colored grid, the pattern jumps out. Plain matplotlib does this with imshow().

Python Correlation heatmap with matplotlib

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.

Notes on the code: vmin=-1, vmax=1 fixes the color scale so that 0 is always the neutral middle, and a diverging colormap (RdBu_r) makes positive and negative correlations look different. Writing the number into each cell lets readers check the exact value. The diagonal is always 1.00 because a column correlates perfectly with itself.

Making charts readable

A short checklist applies to every chart in this lesson:

  • Title with a message. "Order values are right-skewed" tells more than "Histogram of orders".
  • Axis labels with units. "Revenue (USD)" beats "revenue".
  • Sort and order. Sort bars by value; keep time in chronological order.
  • Limit the colors. Use one color for one idea, and a different color only when the meaning changes. Avoid red and green as the only difference, since many people cannot tell them apart.
  • Zero baseline for bars. A truncated bar axis exaggerates differences. Lines and scatter plots do not need zero.
  • Legend only when needed. With a single series, drop it with legend=False.
  • Direct comparisons on one scale. If two charts are meant to be compared, give them the same axis limits.
  • Check small sizes. Fonts and markers that look fine large can be unreadable in a slide or a phone.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A histogram of order values shows a long tail to the right. What is true of the mean and median?

    Large values in the tail pull the mean upward, while the median ignores how large the extreme values are.
  2. 2. Why does the lesson fix a random seed such as default_rng(42)?

    A fixed seed makes the pseudo-random generator repeat the same numbers, so results can be reproduced and checked.
  3. 3. What does signups.rolling(window=7, center=True).mean() produce at the very first row?

    A centered window of 7 needs three values on each side; at the edges they are missing, so the result is NaN (min_periods defaults to the window size).
  4. 4. A scatter plot with a fitted line shows a strong positive slope. What can you conclude?

    A slope shows association. Causation needs more evidence, such as an experiment or a good argument about other factors.
  5. 5. Which choice makes a bar chart of regional revenue easier to read?

    Sorted bars show the ranking at a glance and a unit on the axis prevents guessing. Truncated axes and rainbow colors mislead or distract.

Summary

  • Choose the chart from the question: spread (histogram, box), groups (sorted bars), time (line), two numbers (scatter), many numbers (heatmap).
  • Mark the mean and median on a histogram to show skew.
  • Summarise with groupby() or pivot_table() before drawing bars.
  • Show raw data faintly and a rolling mean boldly to reveal trends.
  • Use np.polyfit() for a trend line and remember it shows association, not cause.
  • A correlation heatmap with a fixed -1 to 1 scale and printed numbers summarises many pairs at once.
  • Readable charts have a message title, labeled axes with units, sensible order and few colors.

Next: Styling and Displaying Tables