Current Affairs updated daily
KalviGavaniKalviGavani

Samacheer Kalvi 12th Computer Science Chapter 16 Data Visualization Using Pyplot Exercise Solutions | KalviGavani

Complete TN Board Class 12 Computer Science Chapter 16 Data Visualization Using Pyplot exercise solutions — matplotlib pyplot, line plots, bar charts, scatter plots, pie charts, histograms, customisation, savefig, and worked Python examples.

Updated 13 June 202612 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

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

FunctionChart TypeUse Case
plt.plot(x, y)LineTrends over time
plt.bar(x, y)BarComparing categories
plt.scatter(x, y)ScatterRelationship between two variables
plt.pie(sizes)PieProportions of a whole
plt.hist(data)HistogramDistribution of continuous data

Customisation Functions

FunctionPurpose
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()
Answer(b) plt.plot() — creates a line plot connecting data points.

Q2. The function plt.bar(x, y) is used to draw:

  • (a) Line chart   (b) Bar chart   (c) Pie chart   (d) Histogram
Answer(b) Bar chart — vertical bars representing categories.

Q3. Which function displays the plot in a window?

  • (a) plt.draw()   (b) plt.display()   (c) plt.show()   (d) plt.print()
Answer(c) plt.show() — renders the plot in an interactive window.

Q4. A histogram is created using:

  • (a) plt.bar()   (b) plt.pie()   (c) plt.hist()   (d) plt.plot()
Answer(c) plt.hist() — groups continuous data into bins and shows frequency distribution.

Q5. Which parameter sets the colour of a plot line?

  • (a) linewidth   (b) color or c   (c) marker   (d) label
Answer(b) color or c — e.g., plt.plot(x, y, color='red') or plt.plot(x, y, c='r').

Q6. To save a plot as an image file, use:

  • (a) plt.save()   (b) plt.write()   (c) plt.savefig()   (d) plt.export()
Answer(c) plt.savefig() — e.g., plt.savefig("chart.png").

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

1. plt.plot() creates a line chart by default.
AnswerTrue 2. plt.show() must be called before plt.savefig() to save the plot correctly. → False — call savefig() before show() because show() may clear the figure. 3. A bar chart and a histogram are the same. → False — a bar chart compares discrete categories; a histogram shows the distribution of continuous data in bins. 4. plt.xlabel() and plt.ylabel() are used to label the axes. → True 5. The label parameter in plt.plot() sets the line label for the legend. → True 6. plt.hist() requires both x and y values. → False — plt.hist(data) only needs the data array; it computes the bins and frequencies automatically.

Match the Following

Column AColumn 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
Answer1-c, 2-e, 3-d, 4-a, 5-b

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="...")
ParameterDescriptionExample
x, yData for X and Y axes[1,2,3], [10,20,15]
colorLine colour'red', 'b', '#FF5733'
markerPoint marker style'o', 's', '^', 'D'
linewidthLine width2, 3
linestyleLine style'-' (solid), '--' (dashed), ':' (dotted)
labelName 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()?

Featureplt.show()plt.savefig()
PurposeDisplays the plot on screenSaves the plot to a file
OutputInteractive windowImage file (PNG, JPG, SVG, PDF)
OrderCall after savefigCall before show
ClearingMay clear the figureDoes 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 point
  • linewidth=2 makes the line thicker
  • grid(True) adds background grid lines
  • label links to the legend via plt.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 names
  • autopct: Format for percentage labels ("%1.1f%%" shows one decimal)
  • explode: Offsets slices from the centre
  • shadow: Adds a shadow effect
  • startangle: 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=5 divides 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 size
  • marker: Shape ('o' circle, 'D' diamond, '^' triangle, 's' square)
  • edgecolors: Border colour of markers
  • alpha: 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 1
  • 1, 2, 2 — 1 row, 2 columns, position 2
  • figsize=(12, 5) sets the overall figure size in inches
  • tight_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

MistakeWhy It's WrongFix
Calling plt.show() before plt.savefig()show() may clear the figureAlways call savefig() before show()
Forgetting plt.show() in scriptsPlot is created in memory but not displayedAlways call plt.show() at the end
Using plt.hist() for categorical dataHistograms are for continuous data distributionsUse plt.bar() for categories
Not using label parameter with plt.legend()Legend appears empty or errorsAdd label="..." in plot calls, then call plt.legend()
Hardcoding colours without checking contrastSome colours are hard to seeUse distinct, high-contrast colours
Overlapping labels in pie chartsToo many small slices make labels unreadableUse autopct for percentages, limit to 5-7 categories
figsize too small or too largeChart looks cramped or stretchedUse plt.figure(figsize=(10, 6)) as a starting point
Using plt.bar() with numerical X dataBar positions may not matchUse 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() and plt.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=...) and plt.subplot() for multiple charts
  • [ ] Can save plots with plt.savefig() before plt.show()
  • [ ] Know the difference between bar chart and histogram
  • [ ] Know the difference between plt.show() and plt.savefig()
  • [ ] Can explain when to use each chart type (line, bar, scatter, pie, histogram)

Frequently Asked Questions

matplotlib.pyplot, commonly imported as plt. It provides functions for creating line plots, bar charts, scatter plots, pie charts, histograms, and more.