Data Visualization in Python: Chart Choice, Worked Example and Exam Traps

Follow five rows from a CSV to a labelled line chart and scatter plot. The worked example also shows how to check the arithmetic and reject misleading conclusions.

KnowledgeGate Team

Exam prep & CS education

Updated 21 Nov 20265 min read
Data Visualization in Python: Chart Choice, Worked Example and Exam Traps

Plotting commands are easy to memorise. The harder part is deciding which chart answers the question, reading its axes, tracing the code and refusing a conclusion that the data cannot support. The five-row CSV below records week, study hours and score; those values support a line chart for trend and a scatter plot for association. A suitable plot has a clear reason for its chart type, axes and conclusion.

1. What data visualization actually encodes

Data visualization maps values to visible properties. An x-position can show a week, a y-position a score, and bar length a magnitude. Colour or shape can distinguish groups. Keep the data, visual encoding and conclusion separate. Decoration is not analysis.

The dataset:

week

hours

score

1

4

42

2

6

51

3

5

49

4

8

63

5

10

71

week is ordered. hours and score are quantitative. Two questions guide the chart choices:

  1. How did score change across weeks?

  2. How do study hours and score move together in these five observations?

2. Choose the chart from the question, not from habit

Use a bar chart to compare discrete categories, a line chart for change across an ordered sequence or time, a histogram for the distribution of one numeric variable, and a scatter plot for the relationship between two numeric variables. Bar-chart categories are separated. Histogram bars touch because they represent adjacent numeric intervals.

For the first question, plot week against score as a line. For the second, plot hours against score as separate scatter points. Five scores are too sparse for a confident histogram claim. Connecting the scatter points would wrongly imply a sequence.

Build this question-first habit in Coding & Skills: identify the problem before choosing the tool.

3. Worked example: CSV rows to a correct score trend

Save this source exactly as mock_progress.csv:

csv
week,hours,score
1,4,42
2,6,51
3,5,49
4,8,63
5,10,71

Load and inspect it before plotting:

python
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("mock_progress.csv")

print(df.shape)                         # (5, 3)
print(df.dtypes)                        # all three columns are numeric
print(df.isna().sum().sum())            # 0 missing values
print(df.duplicated().sum())            # 0 duplicate rows

Now check the summaries. The mean is (42 + 51 + 49 + 63 + 71) / 5 = 276 / 5 = 55.2. The minimum is 42 in week 1, and the maximum is 71 in week 5. The net change is 71 - 42 = 29.

The consecutive changes are 51 - 42 = +9, 49 - 51 = -2, 63 - 49 = +14, and 71 - 63 = +8. Therefore, the largest week-to-week rise is 14 points from week 3 to week 4. The movement is upward overall, but it is not perfectly increasing because week 3 has a 2-point fall.

python
fig, ax = plt.subplots()
ax.plot(df["week"], df["score"], marker="o", label="Score")
ax.axhline(55.2, linestyle="--", label="Mean = 55.2")
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_xlabel("Mock week")
ax.set_ylabel("Score")
ax.set_ylim(0, 80)
ax.set_title("Mock Score by Week")
ax.legend()
plt.show()

Use the Python course to strengthen file handling, pandas-style tabular reasoning and plotting foundations.

Line chart of mock scores 42, 51, 49, 63 and 71 across weeks 1 to 5, with a dashed mean line at 55.2 and the -2 and +14 changes marked.

4. Add a scatter plot and make only the supported claim

The scatter plot contains (4, 42), (6, 51), (5, 49), (8, 63) and (10, 71). Hours are on the x-axis and score is on the y-axis. Week labels trace each point to its row.

python
fig, ax = plt.subplots()
ax.scatter(df["hours"], df["score"])

for _, row in df.iterrows():
    ax.annotate(
        f"W{int(row['week'])}",
        (row["hours"], row["score"]),
        xytext=(4, 4),
        textcoords="offset points"
    )

ax.set_xlabel("Study hours")
ax.set_ylabel("Score")
ax.set_title("Study Hours and Score")
plt.show()

In these five observations, higher study-hour values are associated with higher scores overall. That is all the plot supports. It does not prove that extra hours caused the score increase, and five rows do not justify a claim about all learners.

The line chart answers change by week. The scatter plot answers co-movement between two numeric variables. The same table needs different charts when the question changes.

5. Common visualization traps and their repairs

Three reasoning traps can distort even correct values:

Trap

What goes wrong

Repair

Unsorted ordered x-axis

The sequence is scrambled

Keep weeks in the order 1, 2, 3, 4, 5

Truncated y-axis

Small differences can look dramatic

Show the declared 0 to 80 range and read the tick labels

Unlabelled axis

The reader cannot interpret a value

Label both axes with clear variable names

Three design traps are equally common. A line chart for unrelated categories invents continuity, so use bars. Do not treat histogram bins as categories because they represent numeric intervals. Extra colours, 3D effects or legends that encode no variable add noise, so use the simplest effective encoding.

A zero baseline is especially important when bar length represents magnitude. A line chart can sometimes use a restricted range, but that range must be visible and must never conceal the true size of a change.

The same weekly scores drawn twice: a full 0 to 80 y-axis on the left and a truncated 40 to 75 y-axis that exaggerates the same rise.

6. How exams test data visualization: four traced checks

Four exam-style traces use the same table:

  1. df[df["score"] >= 50] keeps the rows with scores 51, 63 and 71. They belong to weeks 2, 4 and 5, so the result has 3 rows.

  2. df["score"].mean() adds 42 + 51 + 49 + 63 + 71 = 276, then divides by 5. The result is 55.2.

  3. df["score"].diff() subtracts each previous score. Its values are NaN, 9, -2, 14, 8 because the first row has no previous row.

  4. The largest value after that initial NaN is 14. It comes from 63 - 49, so the largest rise is from week 3 to week 4.

Concept questions may ask you to choose line versus scatter, distinguish a bar chart from a histogram, identify the independent variable on the x-axis, or spot a misleading truncated scale. If tracing Python objects and expressions is the difficult part, practise with Python Output-Based Questions before returning to the plotting code.

7. The short version and the next practice step

Use this five-step checklist:

  1. Write the question the chart must answer.

  2. Identify whether each variable is categorical, ordered or quantitative.

  3. Select the chart that matches that question and those variables.

  4. Label the axes and show the scale honestly.

  5. State only the conclusion supported by the plotted rows.

For this dataset, score rose by a net 29 points with one 2-point dip. Hours and scores move upward together in this five-row sample, but the plot does not prove causation.

Use the Python course first for language and visualization foundations. Treat DSA Using Python as a later problem-solving path, not as a visualization course. Classic Programs in C, Java and Python offers further practice in tracing small programs.

Now replace the five scores with your own mock-test scores. Recompute the mean and consecutive differences, then redraw both charts and explain what each one does, and does not, show.