Đại học Kinh tế Quốc dân – National Economics UniversityMICRO4ASIA
🏆 Arena
Sign inSign up
MICRO4ASIAThe six micro-credentials

Courses are delivered on the Limio learning platform. Limio

← Data Cleaning and Preprocessing with Python

You are viewing a public preview

Sign in to save your progress, do assignments, join discussions and get feedback.

Sign in
Module 1 — Explore and Understand the Data

Period 5 · Exploring Sales Data with Charts

Print / Save as PDF
Lecture video — Period 5: Exploring Sales Data with Charts

Histograms, box plots, bar charts and scatter plots: choosing a chart for each question and reading what it can and cannot show.

Lesson overview

In this period, we will use four charts to explore sales data. In Period 4, we described data with summary statistics. Now we will see patterns that a single number may hide. Each chart answers a different question. By the end, you should be able to choose a chart, write the Python code, and explain what the chart suggests. We will also separate an observation from a claim that still needs evidence.

Study notes

By the end of this lesson you can:

  • Choose a histogram, boxplot, bar chart or scatter plot to match a specific question.
  • Read a histogram and explain how bin width changes what you see.
  • Read a boxplot, including the 1.5 x IQR whiskers and separate points.
  • Draw the four charts with pandas and Matplotlib, with labels and units.
  • Write chart comments that separate observation, possible explanation and next check.

Key idea: Start with the question, then choose the chart. Describe what the chart shows, and state clearly what it cannot prove.

Matching the chart to the question

QuestionChartVariable types
How is quantity distributed?HistogramOne numeric
Where is the middle, and are there unusual values?BoxplotOne numeric
How many transactions per region?Bar chartOne categorical
How do quantity and unit price move together?Scatter plotTwo numeric

The lecture uses twelve simulated transactions, four in each region. Quantity counts items; unit price is in thousand Vietnamese dong per item. A quantity of 20 is deliberately included. Before plotting real data, check types and missing values: a missing quantity cannot enter the histogram, so record any excluded rows. Use only the columns each chart needs; the scatter plot needs both quantity and unit price, while the histogram needs only quantity.

Histogram: the shape of a distribution

A histogram divides a numeric range into intervals called bins; each bar's height is the number of observations in that bin. With bins starting at 0, 5, 10, 15, 20 and 25, seven transactions have quantities below 5, four lie between 5 and 10, and one is in the final interval. The long tail on the right suggests right skew. Heights here are counts, not probability density.

Bin width matters. Wide bins merge values and can hide local patterns; narrow bins show detail but make a small sample look irregular. Use equal widths for a fair comparison of counts. Half-unit boundaries (for example 0.5, 1.5, 2.5...) place whole-number quantities inside bins rather than on edges. Try another reasonable width and check that your main observation survives. Never choose bins just to make a preferred story look stronger.

Boxplot: the middle and unusual values

The box runs from Q1 to Q3, and the middle line is the median. In the lecture data the median is 4, Q1 = 2.75 and Q3 = 5.25 (linear interpolation), so IQR = 2.5. The upper limit is Q3 + 1.5 x IQR = 9. The whisker ends at 7, the largest observed value inside that limit, and 20 appears as a separate point.

A separate point is a review flag, not proof of an error. Ask what the transaction represents: a business customer may really buy 20 items, or someone may have typed an extra zero or used a different unit. Check the original record. In exploration we keep the value and document the question; removing it now would change the distribution and might hide genuine customer behaviour.

Bar chart and scatter plot

For the bar chart, decide what each bar measures. Here value_counts() counts transactions, and we put the regions in a fixed order so later outputs are easy to compare. All three regions have four transactions. We can say the sample has equal transaction counts; we cannot say the regions have equal revenue, because the chart shows no prices or quantities. Start the vertical axis at zero so bar lengths represent counts fairly.

A scatter plot keeps the two measurements from each transaction together: quantity on the x-axis, unit price on the y-axis. In the sample, points move downward as quantity increases, a negative association. The transaction at 20 items and 40 thousand dong sits far from the group and may dominate the visual impression. Product differences or pricing rules could explain the pattern; the chart cannot establish cause and effect.

Worked example

The quantities below are one set consistent with the lecture's summary (median 4, Q1 2.75, Q3 5.25, one value of 20); they are illustrative.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

qty = pd.Series([1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 20], name="quantity")
q1, q3 = qty.quantile([0.25, 0.75])
iqr = q3 - q1
upper = q3 + 1.5 * iqr
print(q1, qty.median(), q3, iqr, upper)          # 2.75 4.0 5.25 2.5 9.0
print(qty[qty <= upper].max())                   # 7 -> end of the upper whisker
print(qty[qty > upper].tolist())                 # [20] -> shown as a separate point

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
qty.plot.hist(bins=np.arange(0.5, qty.max() + 1.5, 1), ax=axes[0],
              title="Quantity per transaction")
axes[0].set_xlabel("Items")
axes[1].boxplot(qty.to_numpy())
axes[1].set_title("Quantity (1.5 x IQR whiskers)")
plt.tight_layout()
plt.show()

Expected output: the printed quartiles and fence match the lecture's boxplot (Q1 2.75, median 4, Q3 5.25, upper limit 9), the whisker stops at 7, and 20 is flagged. A good comment on these charts: "Eleven of the twelve transactions contain one to seven items; the order with 20 items should be checked against its record."

Common mistakes

  • Treating a boxplot point as an error. It only marks a value beyond the whisker limit; investigate before acting.
  • Tuning bins to fit a story. Use equal widths, try another reasonable width, and report what stays the same.
  • Reading revenue from a count chart. Equal transaction counts say nothing about sales value.
  • Claiming cause from a scatter plot. A downward pattern is an association; product mix or pricing rules may explain it.

Summary

  • Pick the chart from the question: histogram, boxplot, bar chart or scatter plot.
  • Label every chart with variables and units, and state how many observations it shows.
  • Bin width changes a histogram's look; check that conclusions survive another reasonable width.
  • Boxplot whiskers reach the last value within 1.5 x IQR of the box; points beyond are flags for review.
  • Compare charts only on comparable axis scales, and start bar axes at zero.
  • In every comment, separate what you see, what might explain it and what you would check next.

Flashcards · Exploring Sales Data with Charts

9 words
WordMeaningExample
  • Histogram

    A chart that counts how many values of one numeric variable fall into each interval (bin).

    `df["quantity"].plot.hist(bins=20)`

  • Bin

    One interval of a histogram; its width affects how much detail the chart shows.

    Bins 0-5, 5-10, 10-15 items

  • Right skew

    A distribution with a long tail of large values on the right side.

    Most quantities 1-7, one order of 20 items.

  • Boxplot

    A chart showing the median, Q1 to Q3 box, whiskers within 1.5 x IQR, and points beyond them.

    `plt.boxplot(df["quantity"].to_numpy())`

  • Whisker

    The line from the box to the most extreme observed value still inside the 1.5 x IQR limit.

    Upper limit 9, so the whisker ends at 7.

  • Bar chart

    A chart comparing a count or total across categories; the axis should start at zero.

    `df["region"].value_counts().plot.bar()`

  • Scatter plot

    A chart placing each record as a point using two numeric variables.

    `df.plot.scatter(x="quantity", y="unit_price")`

  • Negative association

    A pattern where one variable tends to decrease as the other increases; it does not prove cause.

    Unit price falls as quantity rises in the sample.

  • value_counts().reindex()

    Counts categories and puts them in a fixed order for consistent charts.

    `.reindex(["North", "South", "Central"])`