Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course
4.3 Data Visualisation and Data Storytelling with SQL and Python
Unit 4 – Data and Analysis · 90 min read · 8 MCQs to check yourself
Data storytelling: how to make your charts more engaging
1. Data storytelling
Data storytelling = data + visuals + narrative: it turns numbers into a clear message that helps people decide.
- Ask a question – “Did online classes change pass rates in our district?”
- Find data – your own survey, school records, or existing datasets: Pakistan Bureau of Statistics (PBS), World Bank Open Data, Kaggle, Our World in Data, FBISE result gazettes.
- Clean and explore – descriptive statistics, several views.
- Find the insight – the most important pattern or change.
- Choose the visual that shows that insight best.
- Tell the story – title that states the message, annotations, context, conclusion, and compare with older stories/data (has the trend changed?).
2. Descriptive statistics – summarise first
| Measure | What it tells | Example (marks 45, 60, 60, 72, 98) |
|---|---|---|
| Mean | average | 67 |
| Median | middle value (resists outliers) | 60 |
| Mode | most common value | 60 |
| Range | max − min | 53 |
| Standard deviation | how spread out the values are | ≈ 17.7 |
| Quartiles / IQR | middle 50% of data – used in box plots | Q1 = 60, Q3 = 72 |
import statistics as st
marks = [45, 60, 60, 72, 98]
print("mean", st.mean(marks), "| median", st.median(marks), "| mode", st.mode(marks))
print("range", max(marks) - min(marks), "| std dev", round(st.pstdev(marks), 1))
Output:
mean 67 | median 60 | mode 60
range 53 | std dev 17.7
Multiple views uncover new insights: two sections may have the same mean but different spread – only a histogram or box plot shows that.
3. Choosing the right chart
| Goal | Chart |
|---|---|
| Compare categories | Bar chart |
| Show a trend over time | Line chart |
| Show parts of a whole (few parts) | Pie chart (or a 100% stacked bar) |
| Show distribution / spread | Histogram, box plot |
| Show a relationship between two numbers | Scatter plot |
| Show values on a map | Choropleth map |
4. Reading and critiquing published visuals
Ask: Who made it and why? Is the data source given? Does the axis start at zero for bars? Are scales consistent? Is it cherry-picked (only some years)? Is correlation presented as causation? Is a 3-D or pie chart hiding differences?
The left chart makes Islamabad look twice as good as Quetta; the honest chart shows a gap of only 11 percentage points.
5. Preparing data with SQL, visualising with Python
SQL summarises the data:
SELECT city, AVG(pass_percent) AS avg_pass
FROM results
GROUP BY city
ORDER BY avg_pass DESC;
Python (pandas + matplotlib) draws the chart:
import sqlite3
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE results (city TEXT, year INTEGER, pass_percent REAL)")
con.executemany("INSERT INTO results VALUES (?, ?, ?)",
[("Islamabad", 2025, 82), ("Lahore", 2025, 79), ("Karachi", 2025, 77),
("Islamabad", 2024, 80), ("Lahore", 2024, 76), ("Karachi", 2024, 75)])
rows = con.execute("""SELECT city, AVG(pass_percent) FROM results
GROUP BY city ORDER BY AVG(pass_percent) DESC""").fetchall()
print(rows)
cities = [r[0] for r in rows]
avg = [r[1] for r in rows]
plt.bar(cities, avg, color="steelblue")
plt.ylim(0, 100)
plt.title("Average pass % 2024–25: Islamabad leads")
plt.ylabel("pass %")
plt.savefig("pass_rates.png")
print("chart saved as pass_rates.png")
Output:
[('Islamabad', 81.0), ('Lahore', 77.5), ('Karachi', 76.0)]
chart saved as pass_rates.png
In R the same chart is barplot(avg, names.arg = cities); in Excel/Google Sheets select the data → Insert → Chart.
Short and long questions
1. How can a published data visualisation mislead? Give three things to check while critiquing it.
Model answer
- Axis manipulation – a bar chart axis not starting at zero exaggerates differences.
- Cherry-picking – showing only selected years or groups.
- Correlation shown as causation, missing data source, or 3-D/pie charts that distort sizes.
2. Calculate the mean, median and mode of 12, 15, 15, 18, 20, 32. Which best represents the data and why?
Model answer
Mean = (12 + 15 + 15 + 18 + 20 + 32) / 6 = 112 / 6 ≈ 18.67; Median = (15 + 18) / 2 = 16.5; Mode = 15. The median best represents the data because the value 32 is an outlier that pulls the mean up.
3. Your college wants to know whether attendance affects final marks. Explain how you would create a data story: formulate the question, identify the dataset, use descriptive statistics to build multiple views, choose and justify visualisations, and present the conclusion. (6)
Model answer
1. Question (1): “Do students with higher attendance score higher final marks, and by how much?”
2. Dataset (1): college records (roll no, attendance %, final marks, section) exported to Excel/SQL; check for missing values and remove duplicates; compare with last year’s results to see if the pattern is new.
3. Descriptive statistics and multiple views (2):
- Mean, median and standard deviation of marks for attendance groups (<60%, 60–80%, >80%) using
GROUP BYin SQL or pandas. - Scatter plot attendance vs marks – shows the relationship and outliers.
- Box plots of marks for each attendance group – show median and spread.
- Bar chart of average marks per group – easy comparison for management.
4. Visual choices (1): scatter for relationship, box plot for distribution, bar chart for summary; axes start at zero, clear titles that state the message (“Students above 80% attendance average 14 marks more”), labelled axes and source.
5. Conclusion (1): state the insight with numbers, note that this is correlation not proof of causation (motivated students may attend more), and recommend actions (attendance alerts) plus a follow-up study.
4. Write SQL and Python (matplotlib) code to find and plot the average marks per subject from a table marks(student, subject, score).
Model answer
SELECT subject, AVG(score) AS avg_score FROM marks GROUP BY subject;
import sqlite3, matplotlib.pyplot as plt
con = sqlite3.connect("school.db")
rows = con.execute("SELECT subject, AVG(score) FROM marks GROUP BY subject").fetchall()
plt.bar([r[0] for r in rows], [r[1] for r in rows])
plt.title("Average marks by subject"); plt.ylabel("marks")
plt.show()
5. What is data storytelling? List its main steps.
Model answer
Data storytelling communicates insights from data using data + visuals + narrative so an audience understands and acts. Steps: ask a question → find/collect data → clean and explore with descriptive statistics → find the key insight → choose a suitable visual → tell the story with a message title, context and conclusion (and compare with earlier data).
6. A team is working on a research project and wants to visually present their conclusions. Which digital tool could they use, and why? (1 + 2)
Model answer
Tool (1): e.g. Microsoft Power BI / Tableau / Google Looker Studio (or Python matplotlib, Excel charts). Why (2): they turn data into clear charts and interactive dashboards, allow filtering and comparisons, connect directly to data sources (Excel, SQL), and are easy to share online – so the audience understands and trusts the conclusions.
7. Write down any three benefits of data visualisation in making data-driven decisions.
Model answer
- Patterns and trends are seen quickly – e.g. falling sales in one region over months.
- Outliers and problems stand out – an unusual spike or a failing branch.
- Complex data becomes easy to communicate to managers and the public, so decisions are faster and better supported. (Also: comparison of options, interactive exploration.)
This lesson ends with a quiz of 8 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 4.2 Evaluating Models: Confusion Matrix, Metrics and Hyperparameter Tuning · Next: 4.4 Hypothesis Testing: Null and Alternative Hypotheses, P-values and Conclusions
All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course