Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📈 Unit 1 – Data Visualisation  ·  Lesson 16

Matplotlib: Line & Bar Charts

What is data visualisation?

Data visualisation means showing data as pictures – charts and graphs – so patterns are seen at a glance. Python's Matplotlib library draws them; its pyplot module is imported as plt.

Command prompt
pip install matplotlib

pyplot basics

  1. 1import matplotlib.pyplot as plt
  2. 2Prepare x and y data (lists, Series)
  3. 3Call a chart function: plot(), bar(), hist(), pie()
  4. 4Add title, labels, legend
  5. 5plt.show() to display or plt.savefig() to save
Every chart in five steps

Line chart

Python
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
temp = [14, 17, 23, 29, 34, 33]
plt.plot(months, temp)
plt.title('Average Temperature in Delhi')
plt.xlabel('Month')
plt.ylabel('Temperature (°C)')
plt.savefig('line_basic.png')
print('Chart saved')
Chart saved
Line chart of monthly temperature in Delhi
Output of the program

Customising a plot

Python
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
delhi = [14, 17, 23, 29, 34, 33]
shimla = [5, 7, 11, 15, 19, 20]
plt.plot(months, delhi, color='red', marker='o', linestyle='-', linewidth=2, label='Delhi')
plt.plot(months, shimla, color='blue', marker='s', linestyle='--', linewidth=2, label='Shimla')
plt.title('Delhi vs Shimla Temperature')
plt.xlabel('Month'); plt.ylabel('°C')
plt.legend()
plt.grid(True)
plt.savefig('line_custom.png')
print('Chart saved')
Chart saved
Two-line chart comparing Delhi and Shimla temperature
Colour, marker, line style, legend and grid

Bar chart

Python
import matplotlib.pyplot as plt
subjects = ['English', 'Maths', 'Physics', 'Chemistry', 'IP']
marks = [82, 91, 76, 68, 95]
plt.bar(subjects, marks, color=['#2563eb', '#16a34a', '#f97316', '#db2777', '#7c3aed'], width=0.6)
plt.title('Marks of Riya – Term 1')
plt.xlabel('Subject'); plt.ylabel('Marks')
plt.ylim(0, 100)
plt.savefig('bar_basic.png')
print('Chart saved')
Chart saved
Bar chart of subject marks
Each bar has its own colour

Multiple bar chart

Shift bars left and right of each x position so two series stand side by side.

Python
import matplotlib.pyplot as plt
import numpy as np
years = ['2021', '2022', '2023', '2024']
boys = [120, 135, 150, 160]
girls = [110, 140, 155, 175]
x = np.arange(len(years))
plt.bar(x - 0.2, boys, width=0.4, label='Boys', color='skyblue')
plt.bar(x + 0.2, girls, width=0.4, label='Girls', color='salmon')
plt.xticks(x, years)
plt.title('Admissions per Year'); plt.xlabel('Year'); plt.ylabel('Students')
plt.legend()
plt.savefig('bar_grouped.png')
print('Chart saved')
Chart saved
Grouped bar chart of boys and girls admissions
Side-by-side bars with xticks

Horizontal bar chart

Python
import matplotlib.pyplot as plt
apps = ['WhatsApp', 'YouTube', 'Instagram', 'Games', 'Study apps']
hours = [1.5, 2.2, 1.1, 0.8, 1.9]
plt.barh(apps, hours, color='teal')
plt.title('Daily Screen Time of a Class 12 Student')
plt.xlabel('Hours per day')
plt.savefig('barh.png')
print('Chart saved')
Chart saved
Horizontal bar chart of daily screen time
barh() is useful when labels are long

Plotting DataFrame columns

Python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
                   'Tea': [45, 52, 40, 60, 58, 75],
                   'Coffee': [30, 28, 35, 33, 40, 55]})
plt.plot(df['Day'], df['Tea'], marker='o', label='Tea')
plt.plot(df['Day'], df['Coffee'], marker='^', label='Coffee')
plt.title('Canteen Sales (cups)'); plt.xlabel('Day'); plt.ylabel('Cups sold')
plt.legend(); plt.grid(alpha=0.3)
plt.savefig('line_from_df.png')
print('Best tea day:', df.loc[df['Tea'].idxmax(), 'Day'])
Best tea day: Sat
Line chart of tea and coffee sales
Columns of a DataFrame used as data

Parameters summary

Function / parameterUse
plt.plot(x, y)Line chart
plt.bar(x, h) / plt.barh(y, w)Vertical / horizontal bars
title(), xlabel(), ylabel()Text on the chart
color / c'red', 'b', '#16a34a'…
marker'o' circle, 's' square, '^' triangle, '*' star
linestyle / ls'-' solid, '--' dashed, ':' dotted, '-.'
linewidth / lw, widthLine thickness / bar width
label + legend()Key that names each series
grid(), xticks(), ylim()Grid lines, tick labels, axis range
savefig(), show()Save to file / display

Frequently Asked Questions

What is the difference between plt.show() and plt.savefig()?
show() opens the chart in a window; savefig("file.png") saves it as an image file. Call savefig before show.
When should I use a line chart and when a bar chart?
Use a line chart for change over time (trend). Use a bar chart to compare separate categories.
Why is the legend empty?
legend() shows the label= given in plot() or bar(). Without label there is nothing to show.
← Class 12 Informatics Practices
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicHistogram, Pie & Pandas Plot Your progress: 16 / 25 (64%) · Lesson 17 / 25 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free