Circle of Learning Logo CIRCLE OF LEARNING Excellence in Education
CBSE Class 12 · Informatics Practices Chapter 3 Session 2026-27

Data Visualization using Matplotlib Formulas & Cheat Sheet

Complete chapter-wise reference, step-by-step formula explanations, structured table, and board exam trap warnings.

Core Concepts & Theoretical Foundations

  • Data Visualization: Graphical representation of information and data using visual elements like charts, graphs, and maps.
  • Matplotlib Pyplot: `matplotlib.pyplot` module provides a state-machine interface for plotting similar to MATLAB.
  • Line Plot: `plt.plot(x, y)` visualizes data trends over a continuous interval or time span.
  • Bar Chart: `plt.bar(x, height)` draws vertical bars for comparing discrete categorical quantities; `plt.barh(y, width)` creates horizontal bars.
  • Histogram: `plt.hist(x, bins=n)` plots frequency distribution of continuous numerical data grouped into equal bin intervals.
  • Chart Customizations: `plt.title()`, `plt.xlabel()`, `plt.ylabel()`, `plt.legend()`, `plt.grid()`, `plt.xticks()`, `plt.yticks()`.
  • Line & Marker Styling: `color` (e.g. 'r', 'blue'), `linestyle` ('-', '--', ':', '-.'), `linewidth`, `marker` ('o', '*', '^', 's'), `markersize`.
  • Saving and Displaying: `plt.show()` renders visual canvas in GUI window; `plt.savefig('plot.png')` exports figure to graphic file.

Chapter Formulas & Equations (12 entries)

# Topic / Formula Name Mathematical Form & Equation Conditions, Meaning & Board Tips
1 Line Plot Generation Syntax
plt.plot(x,y,color=′c′,ls=′−′,lw=w,marker=′m′)\text{plt.plot}(x, y, \text{color}='c', \text{ls}='-', \text{lw}=w, \text{marker}='m')

Plots connected line segments between points (x_i, y_i) to reveal continuous trends.

2 Vertical Bar Chart Syntax
plt.bar(x,height,width=w,color=′c′,edgecolor=′k′)\text{plt.bar}(x, \text{height}, \text{width}=w, \text{color}='c', \text{edgecolor}='k')

Renders vertical bars where height corresponds to category values; width sets bar thickness.

3 Horizontal Bar Chart Syntax
plt.barh(y,width,height=h,color=′c′)\text{plt.barh}(y, \text{width}, \text{height}=h, \text{color}='c')

Draws horizontal bars extending along x-axis with categories positioned on y-axis.

4 Histogram Frequency Distribution Syntax
plt.hist(x,bins=k,edgecolor=′k′,density=False)\text{plt.hist}(x, \text{bins}=k, \text{edgecolor}='k', \text{density}=\text{False})

Divides range of numeric values into k equal intervals (bins) and displays counts per bin.

5 Plot Title and Axis Label Formatting
plt.title(T),plt.xlabel(X),plt.ylabel(Y)\text{plt.title}(T), \quad \text{plt.xlabel}(X), \quad \text{plt.ylabel}(Y)

Annotates the coordinate axes and provides primary chart descriptive heading.

6 Legend Activation Syntax
plt.legend(loc=’best’∣’upper right’)\text{plt.legend}(\text{loc}=\text{'best'} | \text{'upper right'})

Displays legend box matching labeled series plotted with `label='...'` attribute.

7 Grid Display Function
plt.grid(visible=True,ls=’: ’)\text{plt.grid}(\text{visible}=\text{True}, \text{ls}=\text{': '})

Overlays background coordinate gridlines to assist quantitative visual estimation.

8 Axis Limit Scaling Functions
x∈[xmin⁡,xmax⁡],y∈[ymin⁡,ymax⁡]x \in [x_{\min}, x_{\max}], \quad y \in [y_{\min}, y_{\max}]

Manually constrains visible minimum and maximum coordinate ranges of the axes.

9 Figure Export to File Syntax
plt.savefig(filename,dpi=300)\text{plt.savefig}(\text{filename}, \text{dpi}=300)

Saves generated visualization to high-resolution raster or vector image file (PNG, PDF, SVG).

10 Multiple Bar Alignment Shift Formula
xbar1=x−w2,xbar2=x+w2x_{\text{bar1}} = x - \frac{w}{2}, \quad x_{\text{bar2}} = x + \frac{w}{2}

Shifts x coordinates horizontally by half-width to plot side-by-side comparative bars without overlapping.

11 Tick Marks Customization Syntax
plt.xticks(ticks,labels,rotation=θ)\text{plt.xticks}(\text{ticks}, \text{labels}, \text{rotation}=\theta)

Sets tick locations and replaces default numeric markers with custom string labels rotated by theta degrees.

12 Canvas Clearance and Display Syntax
plt.show()  ⟹  Render GUI Window\text{plt.show}() \implies \text{Render GUI Window}

Renders active figure window on screen; execution halts until plot window is dismissed.

Key Scientific Diagrams & Concept Schematics: Data Visualization using Matplotlib

Visual Reference: matplotlib-chart-anatomy

Official NCERT board curriculum concept schematic and mathematical/scientific reference diagram.

Step-by-Step Worked Board Exam Examples

Example 1: Write Python code using Matplotlib to plot a line graph for 'Year' = [2021, 2022, 2023, 2024] and 'Profit' = [45, 60, 55, 75] in lakhs with red dashed line and circle markers. Add suitable title and labels.

Step 1: Import pyplot module: import matplotlib.pyplot as plt

Step 2: Define lists Year and Profit.

Step 3: Call plt.plot(Year, Profit, color='red', linestyle='--', marker='o').

Step 4: Set title and labels: plt.title('Annual Profit Growth'), plt.xlabel('Year'), plt.ylabel('Profit (in Lakhs)').

Step 5: Call plt.show().

Ans: import matplotlib.pyplot as plt year = [2021, 2022, 2023, 2024] profit = [45, 60, 55, 75] plt.plot(year, profit, color='red', linestyle='--', marker='o') plt.title('Annual Profit Growth') plt.xlabel('Year') plt.ylabel('Profit (in Lakhs)') plt.grid(True) plt.show()

Example 2: Write code to draw a histogram for student marks = [45, 52, 60, 72, 85, 90, 65, 78, 88, 92] with 5 bins and black borders, and save it as 'marks_hist.png'.

Step 1: Define marks list.

Step 2: Use plt.hist(marks, bins=5, edgecolor='black', color='skyblue').

Step 3: Save plot with plt.savefig('marks_hist.png') before plt.show().

Ans: import matplotlib.pyplot as plt marks = [45, 52, 60, 72, 85, 90, 65, 78, 88, 92] plt.hist(marks, bins=5, edgecolor='black', color='skyblue') plt.title('Marks Distribution') plt.xlabel('Marks Range') plt.ylabel('Frequency') plt.savefig('marks_hist.png') plt.show()

Common Mistakes to Avoid in Exam

  • Calling `plt.savefig()` AFTER `plt.show()`: `plt.show()` creates a new blank canvas upon closing, causing `plt.savefig()` to save an empty blank image.
  • Confusing Bar Chart and Histogram: Bar charts compare discrete categorical values with spaces between bars; histograms display continuous numerical intervals without gaps.
  • Using `plt.barh(x, y)` with parameters reversed: in horizontal bar charts `y` holds categorical labels and `width` specifies bar length.
  • Forgetting to call `plt.legend()` after adding `label='...'` in `plt.plot()`, which prevents the legend from being displayed.

Target Practice Questions

Q1. Which parameter in plt.plot() is used to change line thickness?

Correct Answer: linewidth (or lw), e.g. plt.plot(x, y, linewidth=3)

Q2. Write the command to display a horizontal bar chart of subjects = ['CS', 'IP', 'Math'] and scores = [92, 95, 88].

Correct Answer: import matplotlib.pyplot as plt plt.barh(['CS', 'IP', 'Math'], [92, 95, 88]) plt.show()

Q3. What does the 'bins' argument signify in plt.hist()?

Correct Answer: It defines the number of equal-width intervals into which the continuous data range is partitioned.

Frequently Asked Questions

Q. What is the difference between a Bar Chart and a Histogram?

A bar chart represents categorical, discrete data with distinct spaces between bars. A histogram displays frequency distribution of continuous numerical data grouped into bins, with no spaces between adjacent intervals.

Q. Why must plt.savefig() be written before plt.show()?

plt.show() displays the figure and resets/clears the current figure canvas. Calling plt.savefig() after plt.show() saves a blank white canvas.

Q. What are the common marker styles in Matplotlib?

Common markers are 'o' (circle), 's' (square), '^' (triangle), 'D' (diamond), '*' (star), and '+' (plus sign).

Q. How can you rotate x-axis labels to prevent overlapping in Matplotlib?

Use `plt.xticks(rotation=45)` or `plt.xticks(rotation='vertical')` to slant label text.

← View All 6 Chapters in Class 12 Informatics Practices Formula Book