Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
Chapter 16 — Data Visualization Using Pyplot: Exercise Solutions Guide
How to Use This Page
1. Attempt every exercise in your Samacheer Kalvi textbook on your own first. 2. Compare your answers with the solutions below — focus on the method, not just the final result. 3. Practise the Python programs on a computer; modify values and observe the output. 4. Review the Common Mistakes and Exam Checklist before your exam.
Key Concepts
Import Convention
import matplotlib.pyplot as plt
Chart Types Overview
| Function | Chart Type | Use Case |
|---|---|---|
plt.plot(x, y) | Line | Trends over time |
plt.bar(x, y) | Bar | Comparing categories |
plt.scatter(x, y) | Scatter | Relationship between two variables |
plt.pie(sizes) | Pie | Proportions of a whole |
plt.hist(data) | Histogram | Distribution of continuous data |
Customisation Functions
| Function | Purpose |
|---|---|
plt.title("...") | Chart title |
plt.xlabel("...") | X-axis label |
plt.ylabel("...") | Y-axis label |
plt.legend() | Show legend |
plt.grid(True) | Show grid lines |
plt.xlim(a, b) | Set X-axis range |
plt.ylim(a, b) | Set Y-axis range |
plt.xticks(vals, labels) | Custom X-axis tick labels |
plt.savefig("file.png") | Save plot to file |
Multiple Choice Questions
Q1. Which function is used to create a line plot?
- (a)
plt.bar()  (b)plt.plot()  (c)plt.scatter()  (d)plt.hist()
Q2. The function plt.bar(x, y) is used to draw:
- (a) Line chart   (b) Bar chart   (c) Pie chart   (d) Histogram
Q3. Which function displays the plot in a window?
- (a)
plt.draw()  (b)plt.display()  (c)plt.show()  (d)plt.print()
Q4. A histogram is created using:
- (a)
plt.bar()  (b)plt.pie()  (c)plt.hist()  (d)plt.plot()
Q5. Which parameter sets the colour of a plot line?
- (a)
linewidth  (b)colororc  (c)marker  (d)label
Q6. To save a plot as an image file, use:
- (a)
plt.save()  (b)plt.write()  (c)plt.savefig()  (d)plt.export()
Fill in the Blanks
1. The module used for data visualization in Python is ______. → matplotlib.pyplot 2. The default alias for matplotlib.pyplot is ______. → plt 3. plt.______() adds a title to the plot. → title 4. plt.______() displays the legend on the plot. → legend 5. A ______ chart shows proportions of a whole as slices. → pie 6. plt.savefig("chart.______") saves the plot in PNG format. → png (also supports .jpg, .svg, .pdf)
True or False
plt.plot() creates a line chart by default.Match the Following
| Column A | Column B |
|---|---|
1. plt.plot() | a. Proportions as slices |
2. plt.bar() | b. Distribution of continuous data |
3. plt.scatter() | c. Trend over time |
4. plt.pie() | d. Relationship between two variables |
5. plt.hist() | e. Comparing categories with bars |
Short Answer Questions
Q1. What is data visualization? Why is matplotlib used?
Data visualization is the graphical representation of data to identify patterns, trends, and relationships quickly.
matplotlib is the most widely used Python library for creating static, animated, and interactive plots. The pyplot module provides a MATLAB-like interface for creating charts with minimal code.
Q2. Write the syntax for plt.plot() and explain its parameters.
plt.plot(x, y, format_string, label="...", color="...", marker="...",
linewidth=n, linestyle="...")
| Parameter | Description | Example |
|---|---|---|
x, y | Data for X and Y axes | [1,2,3], [10,20,15] |
color | Line colour | 'red', 'b', '#FF5733' |
marker | Point marker style | 'o', 's', '^', 'D' |
linewidth | Line width | 2, 3 |
linestyle | Line style | '-' (solid), '--' (dashed), ':' (dotted) |
label | Name for the legend | "Sales 2025" |
Q3. How do you create a bar chart? Give an example.
import matplotlib.pyplot as plt
subjects = ["Tamil", "English", "Maths", "Science"]
marks = [85, 78, 92, 88]
plt.bar(subjects, marks, color=["red", "blue", "green", "orange"])
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.title("Student Marks by Subject")
plt.show()
For horizontal bars, use plt.barh() instead of plt.bar().
Q4. What is a scatter plot? When is it used?
A scatter plot displays individual data points as dots, showing the relationship between two numerical variables. It reveals correlations (positive, negative, or none).
import matplotlib.pyplot as plt
hours = [1, 2, 3, 4, 5, 6]
marks = [40, 55, 60, 70, 80, 85]
plt.scatter(hours, marks, color="blue", marker="o")
plt.xlabel("Hours Studied")
plt.ylabel("Marks Scored")
plt.title("Study Hours vs Marks")
plt.show()
Q5. What is the difference between plt.show() and plt.savefig()?
| Feature | plt.show() | plt.savefig() |
|---|---|---|
| Purpose | Displays the plot on screen | Saves the plot to a file |
| Output | Interactive window | Image file (PNG, JPG, SVG, PDF) |
| Order | Call after savefig | Call before show |
| Clearing | May clear the figure | Does not clear |
plt.plot(x, y)
plt.savefig("chart.png") # Save first
plt.show() # Then display
Detailed Answer Questions
Q1. Write a Python program to create a line plot showing temperature over a week.
import matplotlib.pyplot as plt
# Data
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
temperature = [28, 30, 32, 29, 27, 31, 33]
# Create line plot with customisation
plt.plot(days, temperature, color="red", marker="o", linewidth=2,
linestyle="-", label="Temperature (°C)")
# Customisation
plt.xlabel("Day of the Week")
plt.ylabel("Temperature (°C)")
plt.title("Weekly Temperature Trend")
plt.legend()
plt.grid(True)
# Display
plt.show()
Key points:
marker="o"places circular dots at each data pointlinewidth=2makes the line thickergrid(True)adds background grid lineslabellinks to the legend viaplt.legend()
Q2. Write a Python program to create a bar chart comparing student marks in five subjects.
import matplotlib.pyplot as plt
# Data
subjects = ["Tamil", "English", "Maths", "Science", "Social"]
marks = [88, 75, 95, 82, 70]
# Create bar chart
plt.bar(subjects, marks, color=["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7"],
edgecolor="black", linewidth=1.2)
# Add value labels on top of each bar
for i, v in enumerate(marks):
plt.text(i, v + 1, str(v), ha="center", fontweight="bold")
# Customisation
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.title("Student Marks by Subject")
plt.ylim(0, 105) # Leave space for labels
plt.grid(axis="y", alpha=0.3)
plt.show()
Horizontal bar chart variant:
plt.barh(subjects, marks, color="teal")
plt.xlabel("Marks")
plt.title("Student Marks by Subject (Horizontal)")
plt.show()
Q3. Write a Python program to create a pie chart showing the distribution of household expenses.
import matplotlib.pyplot as plt
# Data
expenses = ["Rent", "Food", "Education", "Transport", "Savings"]
amounts = [15000, 8000, 6000, 3000, 5000]
# Colours and highlight
colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7"]
explode = (0.05, 0, 0, 0, 0) # Slightly pull out "Rent" slice
# Create pie chart
plt.pie(amounts, labels=expenses, colors=colors, explode=explode,
autopct="%1.1f%%", shadow=True, startangle=140)
# autopct shows percentage on each slice
# startangle rotates the chart
plt.title("Monthly Household Expenses")
plt.legend(expenses, loc="upper left")
plt.show()
Key parameters:
labels: Category namesautopct: Format for percentage labels ("%1.1f%%"shows one decimal)explode: Offsets slices from the centreshadow: Adds a shadow effectstartangle: Rotation angle for the first slice
Q4. Write a Python program to create a histogram showing the distribution of marks.
import matplotlib.pyplot as plt
# Data: marks of 30 students
marks = [45, 52, 67, 72, 58, 90, 85, 76, 43, 65,
78, 82, 55, 60, 71, 88, 92, 48, 63, 77,
54, 69, 81, 73, 66, 59, 83, 75, 68, 50]
# Create histogram
plt.hist(marks, bins=5, color="skyblue", edgecolor="black",
alpha=0.8, label="Frequency")
# Customisation
plt.xlabel("Marks Range")
plt.ylabel("Number of Students")
plt.title("Distribution of Student Marks")
plt.legend()
plt.grid(axis="y", alpha=0.3)
plt.show()
Understanding bins:
bins=5divides the range into 5 equal intervals- Each bar's height = number of students in that mark range
- Alternatively, specify custom bins:
bins=[0, 20, 40, 60, 80, 100]
Difference from bar chart: Histogram shows continuous data distribution; bar chart compares discrete categories.
Q5. Write a Python program to create a scatter plot and customise it.
import matplotlib.pyplot as plt
# Data: study hours vs marks
hours = [1, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6]
marks = [35, 45, 50, 55, 60, 65, 70, 78, 82, 90]
# Create scatter plot
plt.scatter(hours, marks, color="blue", marker="D", s=100,
edgecolors="black", linewidths=1, label="Students")
# Add a trend line (optional)
import numpy as np
z = np.polyfit(hours, marks, 1) # Linear fit
p = np.poly1d(z)
plt.plot(hours, p(hours), color="red", linestyle="--",
linewidth=1.5, label="Trend Line")
# Customisation
plt.xlabel("Hours Studied per Day")
plt.ylabel("Marks Scored")
plt.title("Correlation: Study Hours vs Marks")
plt.legend()
plt.grid(True, alpha=0.3)
plt.xlim(0, 7)
plt.ylim(0, 100)
plt.show()
Key scatter parameters:
s: Marker sizemarker: Shape ('o'circle,'D'diamond,'^'triangle,'s'square)edgecolors: Border colour of markersalpha: Transparency (0.0 to 1.0)
Q6. Write a Python program that uses plt.figure() and plt.subplot() to display multiple charts.
import matplotlib.pyplot as plt
# Data
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
temp = [28, 30, 32, 29, 27]
rainfall = [5, 0, 2, 15, 8]
# Create a figure with 2 subplots (1 row, 2 columns)
plt.figure(figsize=(12, 5))
# Subplot 1: Line chart
plt.subplot(1, 2, 1)
plt.plot(days, temp, color="red", marker="o", linewidth=2)
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.title("Temperature Trend")
plt.grid(True)
# Subplot 2: Bar chart
plt.subplot(1, 2, 2)
plt.bar(days, rainfall, color="skyblue", edgecolor="black")
plt.xlabel("Day")
plt.ylabel("Rainfall (mm)")
plt.title("Rainfall")
plt.grid(axis="y", alpha=0.3)
# Adjust layout and show
plt.tight_layout()
plt.show()
plt.subplot(rows, cols, index):
1, 2, 1— 1 row, 2 columns, position 11, 2, 2— 1 row, 2 columns, position 2figsize=(12, 5)sets the overall figure size in inchestight_layout()prevents overlap between subplots
Q7. Write a Python program that saves a plot to a file using plt.savefig().
import matplotlib.pyplot as plt
# Data
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [120, 150, 180, 200, 170, 220]
# Create plot
plt.plot(months, sales, color="green", marker="s", linewidth=2,
linestyle="-", label="Sales 2025")
plt.xlabel("Month")
plt.ylabel("Sales (units)")
plt.title("Monthly Sales Report")
plt.legend()
plt.grid(True)
# Save to file BEFORE show()
plt.savefig("sales_report.png", dpi=150, bbox_inches="tight")
plt.savefig("sales_report.pdf") # Can save as PDF too
# Display
plt.show()
Key savefig parameters:
dpi: Resolution (default 100; use 150-300 for print quality)bbox_inches="tight": Prevents labels from being cut off- Supports formats: PNG, JPG, SVG, PDF, EPS
Common Mistakes
| Mistake | Why It's Wrong | Fix |
|---|---|---|
Calling plt.show() before plt.savefig() | show() may clear the figure | Always call savefig() before show() |
Forgetting plt.show() in scripts | Plot is created in memory but not displayed | Always call plt.show() at the end |
Using plt.hist() for categorical data | Histograms are for continuous data distributions | Use plt.bar() for categories |
Not using label parameter with plt.legend() | Legend appears empty or errors | Add label="..." in plot calls, then call plt.legend() |
| Hardcoding colours without checking contrast | Some colours are hard to see | Use distinct, high-contrast colours |
| Overlapping labels in pie charts | Too many small slices make labels unreadable | Use autopct for percentages, limit to 5-7 categories |
figsize too small or too large | Chart looks cramped or stretched | Use plt.figure(figsize=(10, 6)) as a starting point |
Using plt.bar() with numerical X data | Bar positions may not match | Use plt.bar() for categorical X; plt.hist() for binned numerical data |
Exam Checklist
- [ ] Can import
matplotlib.pyplot as plt - [ ] Can create line plots with
plt.plot()and customise colour, marker, linestyle - [ ] Can create bar charts with
plt.bar()andplt.barh() - [ ] Can create scatter plots with
plt.scatter() - [ ] Can create pie charts with
plt.pie()including labels, autopct, explode - [ ] Can create histograms with
plt.hist()and understand bins - [ ] Can add title, xlabel, ylabel, legend, grid to any chart
- [ ] Can use
plt.figure(figsize=...)andplt.subplot()for multiple charts - [ ] Can save plots with
plt.savefig()beforeplt.show() - [ ] Know the difference between bar chart and histogram
- [ ] Know the difference between
plt.show()andplt.savefig() - [ ] Can explain when to use each chart type (line, bar, scatter, pie, histogram)
