Chapter 04f · Computer Science
26 blocks · bilingual

Programming In Python - 4.6 Introduction To Data Visualization

LiveBilingual master notes · switch to नेपाली for the full glossary

Complete bilingual study notes for Programming In Python - 4.6 Introduction To Data Visualization — every concept explained step by step, with definitions, formulas, and worked examples.

4.7 Introduction to Data Visualization Using Matplotlib

Data Visualization is the process of representing information and data in the form of visual elements such as graphs, charts, and plots, instead of raw numbers, so that patterns, trends, and insights can be recognized quickly.

  • Quick Understanding of large data
  • Recognize Trends and Patterns
  • Better Decision-Making
  • Clear Presentation for Everyone
  • Spot Outliers and Errors
  • Storytelling with Data

Example set of Matplotlib chart types side by side: a line chart, a pie chart, and a bar chart, each with title and axis labels.

i) Line Chart

A line chart connects points of data using straight lines. It is often used to show trends over time.

import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 20, 30, 40, 50] plt.plot(x, y, label="Marks Obtained") plt.title("Marks Progress") plt.xlabel("Test Number") plt.ylabel("Marks") plt.grid() plt.legend() plt.show()

A multi-line chart can compare two data series by plotting two plt.plot() calls with different colors, linestyles ('--' dashed, ':' dotted), and markers ('o' circle, 's' square) before calling plt.show().

ii) Pie Chart

A pie chart is a circular graph where the whole circle represents 100%, and each slice shows the relative size of a data part. It is used to show proportions and percentages clearly.

import matplotlib.pyplot as plt sizes = [45, 30, 15, 10] labels = ['Windows', 'Mac', 'Linux', 'Others'] colors = ['lightblue', 'lightgreen', 'orange', 'grey'] explode = (0.1, 0, 0, 0) plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140, explode=explode) plt.title('Operating System Market Share') plt.show()

iii) Bar Chart

A bar chart uses rectangular bars to show and compare different categories of data. Bars can be displayed vertically (plt.bar()) or horizontally (plt.barh()).

import matplotlib.pyplot as plt products = ['Pens', 'Notebooks', 'Erasers', 'Markers'] sales = [120, 340, 100, 280] plt.bar(products, sales, color='skyblue') plt.title("Product Sales") plt.xlabel("Products") plt.ylabel("Number of Sales") plt.show()

import matplotlib.pyplot as plt subjects = ['Math', 'Science', 'English', 'Computer'] votes = [45, 50, 30, 60] plt.barh(subjects, votes, color='lightgreen') plt.title("Favorite Subjects of Students") plt.xlabel("Number of Students") plt.ylabel("Subjects") plt.show()

Common Mistakes

  • Forgetting to import the correct library before using its functions (e.g. using math.sqrt() without import math)
  • Using the library name as a prefix after using 'from library import function' (unnecessary and causes an error)
  • Forgetting the colon (:) after try, except, if, or for statements
  • Using a bare except: for every error instead of specifying error types like ZeroDivisionError or ValueError when specific handling is needed
  • Forgetting to close a file using close() after opening it
  • Opening a file in 'w' mode when 'a' (append) mode was intended — this deletes existing content
  • Forgetting newline="" while writing CSV files with the csv module, causing extra blank lines
  • Forgetting index=False while saving a DataFrame to CSV using pandas, which adds an unwanted index column
  • Mixing up plt.bar() (vertical) and plt.barh() (horizontal)
  • Forgetting plt.show() at the end of a Matplotlib program, so the chart does not appear

SEE Exam Tips

  • Read the question carefully to check whether it asks to write, trace, or debug a program.
  • Always write import statements at the top of a program.
  • Write complete programs including opening, using, and closing files.
  • Show the check for the file modes and CSV parameters clearly.
  • Trace loops and conditions carefully before writing the output of a program.
  • Use tables to write differences (e.g., read() vs readline(), csv module vs pandas).
  • Label chart titles, x-axis, and y-axis clearly in diagram-based answers.
  • Do not omit important steps such as file.close() or plt.show().

Quick Revision

  • Library = collection of reusable functions and modules; import using import, from...import, or from...import *
  • math library: sqrt(), pow(), floor(), ceil(), factorial(), degrees(), radians(), sin(), cos(), fabs()
  • random library: random(), randint(a,b), randrange(start,stop), choice(seq), shuffle(list), uniform(a,b)
  • Turtle commands: forward(), backward(), left(), right(), penup(), pendown(), color(), shape(), circle(), begin_fill()/end_fill()
  • Error types: Syntax Error, Runtime Error, Logical Error
  • try-except-else-finally structure handles errors gracefully
  • File modes: r (read), w (write, overwrites), a (append)
  • File operations: open(), read(), readline(), readlines(), write(), close()
  • csv module: csv.writer() and csv.writerow() to write; csv.reader() to read
  • pandas: pd.read_csv(), DataFrame.to_csv(index=False), head(), tail(), shape, columns, mean()
  • Matplotlib charts: plt.plot() (line), plt.pie() (pie, with autopct, explode), plt.bar()/plt.barh() (bar), always end with plt.show()

SEE Important Areas

  • Difference between the three ways of importing a library
  • Common math and random library functions and their outputs
  • Writing simple turtle programs to draw shapes (square, triangle) and using fill
  • Writing try-except-finally programs to handle invalid input and division by zero
  • Writing programs to create, read, and append text files
  • Writing and reading CSV files using both the csv module and pandas
  • Explaining the purpose of index=False in to_csv()
  • Writing programs to create line, pie, and bar charts with proper titles and labels