…
…
Statistics and Data Analysis Fundamentals · Lesson 17 / 44 · Spread, shape, and charts
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Bazaar's management sent three questions for the Monday meeting: which category brings in the most revenue, how did orders change from month to month, and on which device did the drop happen? The same file also has a bar chart made by an intern. It says "Book sales are not even half of Beauty." In this lesson you will choose the right chart for each question, write the result in the title, and find and fix the error in the intern's chart.
At the end of the lesson you will draw the chart below yourself. Look at its title: it does not name the topic of the chart. It says what the chart shows.
orders · Bazaar orders.csv (fictional sample data)
| — | mobile | desktop |
|---|---|---|
| Jan | 89 | 65 |
| Feb | 104 | 73 |
| Mar | 117 | 59 |
| Apr | 97 | 65 |
| May | 56 | 56 |
| Jun | 53 | 51 |
In this lesson you will:
In this unit you saw a distribution (histogram), summarized it (mean, median, standard deviation), located values in it (quartiles, z-score), and put groups side by side with boxplots. One step is left: to show what you found to someone else. The manager in the meeting will not see your code, and will not read your tables row by row. A chart will appear on the screen and, in a few seconds, it will lead to a conclusion. Whether that conclusion is correct depends mostly on two decisions you made: which chart you chose, and how you drew it.
Many people think chart choice is a matter of taste: "bars look nicer," "a pie is more colorful." But each chart type asks the eye to do a different job. In a bar chart, the eye compares lengths. In a line chart, the eye joins the points from left to right and looks for a trend. In a scatter plot, the eye checks whether the points gather along one direction. If you choose the wrong chart, the eye does the wrong job, and the reader sees something the data does not say.
Before you open a chart, write the question in one sentence. Then look at the verb of that sentence. Let's read the three meeting questions this way, plus two more:
| Question sentence | Verb | Chart |
|---|---|---|
| Which category brings in the most revenue? | compare | bar |
| How did orders change from month to month? | track over time | line |
| Do visitors increase when ad spend increases? | look for a relationship | scatter |
| How are order amounts distributed? | look at the distribution | histogram (boxplot if there are groups) |
There is no pie chart in this table. A pie chart is often used to show the shares of a whole, but our eyes do not compare angles and areas as well as they compare lengths. With two slices there is no problem. With five categories, it is hard to say from a pie whether the slice for Books or the slice for Beauty is bigger. The same shares are easy to read in a sorted bar chart at a glance. The rule is simple: with more than three slices, drop the pie and show the shares with a sorted bar chart.
Notice that the "look at the distribution" row comes from earlier lessons in this unit: the histogram from lesson 11 for the distribution of one variable, and the boxplot from lesson 15 for putting the distributions of groups side by side. The bar and the line are new. In this lesson we will take only a first look at the scatter plot. You will see the details in the relationships unit.
Which chart type fits each question?
For each row, pick its match from the list, then check.
The first question is a comparison: the revenue of five categories. To compare one number across categories, use a bar chart. In matplotlib, a vertical bar is drawn with ax.bar(labels, values) and a horizontal bar with ax.barh(labels, values). When category names are long (like Home & Living), horizontal bars are easier to read, because the names are written on the left, one under the other, and do not run into each other.
Do one more thing: sort the bars by value. The result of groupby lists the categories in alphabetical order, and the alphabet has nothing to do with the question "which is the biggest?" In a sorted bar chart, the largest value sits at one end and the smallest at the other, and the ranking is visible at a glance. If the categories have no natural order of their own (months, age groups, satisfaction scores), a sorted bar chart is almost always better. To keep this example simple, it uses all orders (returned and canceled included), and we divide by 1000 to show revenue in thousands of dollars:
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") revenue = orders.groupby("category")["amount"].sum().sort_values() / 1000 fig, ax = plt.subplots() ax.barh(revenue.index, revenue.values) ax.set_xlabel("Revenue ($ thousands)") ax.set_title("Electronics brings in the most revenue") print([round(float(p.get_width()), 2) for p in ax.patches])
Output[2.55, 3.85, 18.23, 19.36, 22.85]ax.patches is the list of bars that were drawn. The length of a horizontal bar is read with get_width() (for a vertical bar, use get_height()). The bars were drawn in the order of the Series, from small to large: Books $2.55, Beauty $3.85, Clothing $18.23, Home & Living $19.36, and Electronics $22.85 thousand. barh puts the first bar at the bottom, so Electronics is at the top of the chart. The title is not "Revenue by category." It says what the chart says: "Electronics brings in the most revenue."
Now run the same chart yourself and change the question. If you ask for the number of orders instead of revenue, does the ranking change?
Try it now· not graded; doesn't affect progress
Revenue and number of orders give different rankings. Clothing gets the most orders, but Electronics is ahead in revenue because it sells more expensive products. Both charts are correct. Which one you show depends on what the question is. This is why the question sentence comes before the chart.
The second question is about time: how did orders change from month to month? To show how a value changes over time, use a line chart: ax.plot(x, y, marker="o"). marker="o" marks each month's value with a dot, and the line joins these dots in order. The eye follows the line from left to right and asks: "Is it going up or down? Where did it break?"
This strength of the line depends on one condition: the x axis must be in order. The line joins the points in the order they are given. If the months come in mixed order, the line zigzags back and forth. In lesson 6 you got the month from a date. Do not forget to put the month counts in month order with sort_index():
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") orders["date"] = pd.to_datetime(orders["date"]) orders["month"] = orders["date"].dt.month monthly = orders["month"].value_counts().sort_index() fig, ax = plt.subplots() ax.plot(monthly.index, monthly.values, marker="o") ax.set_xlabel("Month") ax.set_ylabel("Number of orders") ax.set_title("Orders dropped in May") print(monthly.tolist())
Output[154, 177, 176, 162, 112, 104]From January to June: 154, 177, 176, 162, 112, 104. There is a peak in February and March, a small decline in April, and a sharp break in May. Going from 162 in April to 112 in May is a drop of about 31 percent. You could see this break in the table too, but in the line it is the first thing the eye catches.
Which chart is suitable for showing how the monthly order count changes over time?
Remember that a line suggests a "transition." When you draw a line between two points, you tell the reader, "there is continuity between these two values; one turns into the other." The transition from January to February makes sense: time passes, and on the days in between, the order count really does move from one value to the other. But what happens if you join the revenue of categories with a line?
A report shows the revenue of five categories (Electronics, Home & Living, Clothing, Books, Beauty) by joining the points with a line. What wrong idea does this chart give the reader?
The third question follows the second: on which device did the drop happen? For this, we draw two series, mobile and desktop order counts, as two lines on the same axis. Each ax.plot call adds one line. So that the reader can tell which line is which, give each line a name such as label="mobile", then add the key box with ax.legend(). The month and device table you built in lesson 8 is useful here: groupby(["month", "device"]).size().unstack() puts each device in its own column, and each column becomes a line.
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") orders["month"] = pd.to_datetime(orders["date"]).dt.month t = orders.groupby(["month", "device"]).size().unstack() fig, ax = plt.subplots() ax.plot(t.index, t["mobile"], marker="o", label="mobile") ax.plot(t.index, t["desktop"], marker="o", label="desktop") ax.set_ylim(bottom=0) ax.legend() print(t)
Outputdevice desktop mobile
month
1 65 89
2 73 104
3 59 117
4 65 97
5 56 56
6 51 53The table and the chart carry the same numbers, but the chart shows right away what the table hides. The desktop line runs like a flat band between 51 and 73 for six months. The mobile line falls from 117 in March to 56 in May. From April to May, 50 orders were lost in total: 41 on mobile and 9 on desktop. The drop is almost entirely on mobile. ax.set_ylim(bottom=0) starts the vertical axis at zero. You will see in a moment why this matters.
Put the lines that draw mobile and desktop orders by month as two lines in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The chart is drawn. Now we need to write the right title for it. In the cell below the chart is ready, but the title only names the topic:
Try it now· not graded; doesn't affect progress
Now let's come to the intern's chart. The chart shows the number of orders by category with bars, and its title says "Book sales are not even half of Beauty." The real numbers: Books 117, Beauty 138, Electronics 156, Home & Living 208, Clothing 266. Is 117 half of 138? No, it is 85 percent. So why does the chart show it that way?
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") counts = orders["category"].value_counts().sort_values() fig, ax = plt.subplots() ax.bar(counts.index, counts.values) ax.set_ylim(100, 280) bottom = ax.get_ylim()[0] for name in ["Books", "Beauty"]: print(name, "real:", counts[name], "· visible height:", counts[name] - bottom)
OutputBooks real: 117 · visible height: 17.0
Beauty real: 138 · visible height: 38.0The problem is in the line ax.set_ylim(100, 280): the vertical axis starts at 100, not at 0. In a bar chart, the eye measures the height of the bar and takes the height to be the value. When the axis starts at 100, the part below 100 is cut off. On the screen, the Books bar is 17 units tall and the Beauty bar is 38 units tall. 17 is less than half of 38. The chart shouts "Books are not even half of Beauty," but the real ratio is 117 / 138, which is 0.85.
The more you cut off, the bigger the mistake. In the block below, change the lower limit of the axis and see how far the visible height ratio moves away from the real ratio:
Change the lower limit of the axis: how far does the visible height ratio of the Books and Beauty bars move away from the real ratio?
Pick a value; predict the output first, then look.
1axis_bottom = 02books, beauty = 117, 1383visible_books = books - axis_bottom4visible_beauty = beauty - axis_bottom5print("Visible heights:", visible_books, "and", visible_beauty)6print("Visible ratio:", round(visible_books / visible_beauty, 2))7print("Real ratio:", round(books / beauty, 2))
Visible heights: 117 and 138 Visible ratio: 0.85 Real ratio: 0.85
Faded lines didn't run with this value. When the axis starts at 0, the visible ratio equals the real ratio: 0.85. With a lower limit of 50 it falls to 0.76, and with 100 it falls to 0.45, so Books looks shorter than half of Beauty. The numbers never changed. Only the axis was cut. In a bar chart, the value axis always starts at 0.
This rule is strict for bars, because the whole meaning of a bar chart is a comparison of lengths. In a line chart the situation is a little different: in a line, the eye does not look at length but at the up and down movement of the points. If you draw a week of body temperature on an axis that starts at 0 degrees, a fever between 36.5 and 38.5 becomes almost a flat line. Here it is fair to narrow the axis to 35–40. So "cutting an axis is always a trick" is not true, and "it is never a problem" is not true either. The rule is this: a bar must start at zero. In a line, the axis may be narrowed, but where the axis starts must be clearly visible, and a small wobble must not be presented as a big collapse. In our device chart we started the axis at zero, because for the question "how big is the drop?" the reader needed to see the scale correctly.
You chose the right chart type and built an honest axis. Two decisions are left: color and title. There is a simple test of a chart's success: can the reader reach the right conclusion in five seconds? In a meeting, nobody looks at a chart for a minute.
Color should carry meaning. Painting every series a different, bright color makes the chart look lively, but it tells the reader "everything is equally important." If there is one series you want to talk about, draw it in color and draw the others in gray. In the device chart, the story is on mobile. If you make the mobile line blue (color="C0") and the desktop line gray (color="gray"), the eye goes to the blue first. Random colors, shadows, and three-dimensional effects do not make a chart better. They distract the reader.
The title should state the result. "Monthly number of orders" is a topic title: it tells the reader what to look at, but not what they will see. "The drop is on mobile: April 97, May 56" is a headline: it gives the result and supports it with numbers. A newspaper does not print "Weather" as a headline. It prints "Snow expected tomorrow."
A title that states a result has a limit: it cannot claim something that is not visible in the chart. "The new checkout page lowered mobile sales" would be an attractive headline, but the chart does not show a cause. It shows only when the drop happened and on which device. Finding the cause is a separate job. The title says only as much as the chart can carry. Do not forget to write the unit in the axis names: "Number of orders," "Revenue ($ thousands)," "Delivery time (days)."
There are two titles for the same two-line chart. A: "Monthly number of orders" (both lines bright, in different colors). B: "The drop is on mobile: April 97, May 56" (mobile blue, desktop gray). Which one gives the right conclusion in five seconds in a meeting?
Misleading charts do not appear only in intern presentations. You will meet them in the news, in ads, and on social media. Most of them come from carelessness, not bad intent, but the effect on the reader is the same. A fictional example: a news site publishes a bar chart with the headline "Rent increases slowed down." The bars show the average rent in a city: $490 in 2023, $520 in 2024, and $535 in 2025 (example, fictional numbers). The vertical axis starts at 475.
import matplotlib.pyplot as plt years = ["2023", "2024", "2025"] rent = [490, 520, 535] bottom = 475 fig, ax = plt.subplots() ax.bar(years, rent) ax.set_ylim(bottom, 550) print("Visible heights:", [r - bottom for r in rent]) print("Increase (%):", round((520 - 490) / 490 * 100, 1), round((535 - 520) / 520 * 100, 1))
OutputVisible heights: [15, 45, 60]
Increase (%): 6.1 2.9There are two problems. The first is the axis: on an axis that starts at 475, the 2025 bar looks four times as tall as the 2023 bar (60 against 15). The reader gets the impression that "rents quadrupled in two years," but the increase is about 9 percent. The second problem is that the title and the chart do not say the same thing. The title talks about the speed of the increase (it fell from 6.1 percent to 2.9 percent, so it really did slow down), but the bars show the level of rent and give the eye a steep climb. The reader is caught between the title and the picture. There are two ways to fix it. If you want to show the rent level, start the axis at 0 and write the title about the level ("Average rent rose from $490 to $535 in two years"). If you want to show the slowdown, draw the yearly increase percentages (6.1 and 2.9) as bars that start at zero, and make the title "Rent increases slowed down: from 6.1 percent to 2.9 percent."
Let's add two more errors to these two. Dual axis: putting two series with different scales (for example, revenue in millions of dollars and order counts in the hundreds) in the same chart with two separate y axes. Since you can set the scale of each axis as you like, you can make the two lines cross, or lie on top of each other, wherever you want. The reader sees a relationship that is not there. Showing a distribution with a single bar: comparing the delivery time of two carriers with only one mean bar each hides the spread and the extreme values you saw in lesson 15. A boxplot is needed there.
Match each description of a faulty chart with the name of its error.
For each row, pick its match from the list, then check.
Meet two more chart types outside the main flow. You are not expected to use them in this unit.
A stacked bar compares the parts of a whole across groups. For example, how much of the mobile and desktop orders were completed, and how much were returned or canceled. pandas draws the share table you built in lesson 8 with crosstab(..., normalize="index") in one line: table.plot(kind="bar", stacked=True, ax=ax). pandas charts are also drawn with matplotlib. When you pass ax=ax, you still add the title and axis names through ax. A stacked bar does the job a pie chart tries to do, and it does it more readably, because it puts the two groups side by side.
A scatter plot shows the relationship between two numeric variables: one point per day, with ad spend on the horizontal axis and the visitor count on the vertical axis. It is drawn with ax.scatter(x, y, alpha=0.5). alpha makes the points semi-transparent and makes overlapping points visible. If the points rise toward the right, the two variables increase together. You will see how to measure the strength of this relationship, and the question "does increasing together mean causing?", in detail in the relationships unit. The code and output for both are in the examples below.
With this lesson, the unit "Seeing and summarizing a distribution" is finished. You saw a distribution with a histogram, summarized it with the mean, median, and standard deviation, located a value with quartiles and the z-score, and now you have learned to show what you found with the right chart. In the unit task you will combine these four steps on new data. In the next unit you will look at data with a very different eye. Up to here the Bazaar data was clean. In real life, data comes with gaps, spelling mistakes, and inconsistent records. The doubt you gained while reading charts, "is this picture telling the truth?", will help you there too.
The final version of the device chart that goes to the meeting: mobile in color, desktop in gray, axis from zero, and the title states the finding with numbers.
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") orders["month"] = pd.to_datetime(orders["date"]).dt.month t = orders.groupby(["month", "device"]).size().unstack() fig, ax = plt.subplots() ax.plot(t.index, t["mobile"], marker="o", color="C0", label="mobile") ax.plot(t.index, t["desktop"], marker="o", color="gray", label="desktop") ax.set_ylim(bottom=0) ax.set_xlabel("Month") ax.set_ylabel("Number of orders") ax.set_title("The drop is on mobile: April 97, May 56") ax.legend() print(ax.get_title()) print([l.get_label() for l in ax.get_lines()], [l.get_color() for l in ax.get_lines()])
OutputThe drop is on mobile: April 97, May 56
['mobile', 'desktop'] ['C0', 'gray']Drawing the monthly line from the value_counts() result without sorting it:
monthly = orders["month"].value_counts() ax.plot(monthly.index, monthly.values, marker="o")
The result of value_counts() lists values from the most frequent to the rarest: the months come in the order 2, 3, 4, 1, 5, 6 (177, 176, 162, 154, 112, 104). The line joins the points in this order: from February to March, to April, then back to January, then forward to May. The result is a line that crosses over itself and zigzags, and no trend can be read. There is no error message either. The code quietly draws a wrong picture. The right way is to put the months in their own order before drawing: monthly = orders["month"].value_counts().sort_index(). In a line chart, the x axis must always be in order.
Next lesson: We are moving to a new unit. Up to here you worked with clean data. Now you will look at raw data full of gaps, errors, and inconsistent records, and assess its quality.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
ax.get_lines() is the list of lines that were drawn. You can read the label and color of each line. "C0" is the first default color of matplotlib (blue). This chart is the same as the target chart at the start of the lesson.
How much of the mobile and desktop orders were completed, returned, or canceled?
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") table = pd.crosstab(orders["device"], orders["status"], normalize="index").round(3) fig, ax = plt.subplots() table.plot(kind="bar", stacked=True, ax=ax) ax.set_ylabel("Share") ax.set_title("The return share is slightly higher on mobile") print(table)
Outputstatus canceled completed returned
device
desktop 0.041 0.897 0.062
mobile 0.037 0.884 0.079Each bar is one device and has a height of 1 (100 percent). The three parts inside are the status shares. The return share is 7.9 percent on mobile and 6.2 percent on desktop. The difference is small, and the title does not exaggerate it: it says "slightly."
Is there a relationship between ad spend and the number of visitors? One point per day:
import pandas as pd import matplotlib.pyplot as plt m = pd.read_csv("marketing.csv") fig, ax = plt.subplots() ax.scatter(m["ad_spend"], m["visitors"], alpha=0.5) ax.set_xlabel("Ad spend ($)") ax.set_ylabel("Visitors") print(len(ax.collections[0].get_offsets())) print(m.groupby(m["ad_spend"] > 100)["visitors"].mean().round(0))
Output181
ad_spend
False 1264.0
True 1553.0
Name: visitors, dtype: float64181 days, 181 points. On days when more than $100 was spent on ads, the average number of visitors is 1,553. On the other days it is 1,264. The points seem to rise toward the right, but measuring the strength of this relationship, and whether it is causal, is the job of the relationships unit.