Purpose of plotting
Data visualization means turning numbers into pictures such as charts and graphs. We plot data because:
- patterns (going up, going down, repeating) are seen in one look;
- comparing groups is quicker than reading many numbers;
- unusual values (outliers) stand out;
- a picture is easier to share and explain in a report.
import matplotlib.pyplot as plt # pyplot = the plotting part of Matplotlib
Every chart follows the same idea: make the chart, decorate it, then plt.show() or plt.savefig().
Line plot
A line plot marks points and joins them in order. Use it when the x-axis is time or order (days, months, years).
month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] sales = [20, 35, 30, 45, 50, 60] plt.plot(month, sales, color='b', marker='o', linestyle='-', linewidth=2) plt.show()
Options: color (e.g. 'r', 'green'), marker ('o', '*', 's'), linestyle ('-', '--', ':'), linewidth, markersize.
Bar graph
A bar graph draws one bar per group. The height shows the value. Use it to compare separate things (subjects, cities, products).
subject = ['Eng', 'Hindi', 'Maths', 'Sci', 'SSt'] marks = [78, 85, 92, 70, 88] plt.bar(subject, marks, color='teal', width=0.6) plt.barh(subject, marks) # horizontal bars plt.show()
Histogram
A histogram shows how values are spread. The range of data is cut into equal parts called bins. Each value falls into one bin, and the bar height is how many values fell there (the frequency). Bars touch each other, because the ranges are continuous.
marks = [35,42,48,51,55,58,61,63,66,68,72,74,79,85,93] plt.hist(marks, bins=[30,44,58,72,86,100], edgecolor='black') plt.hist(marks, bins=5) # 5 equal bins from min to max
A value on an edge (like 58) goes into the bin on its right; only the last bin includes its right edge. histtype='step' draws just the outline.
Bar graph or histogram?
Bar graph: separate groups, gaps between bars, any order. Histogram: one number column cut into ranges, no gaps, fixed order.
Title, labels and legend
plt.plot(month, shopA, label='Shop A')
plt.plot(month, shopB, label='Shop B')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales (in thousand โน)')
plt.legend() # shows the label= names in a box
plt.grid(True)
plt.show()A legend is the small key that tells which colour is which line. It needs label= in each plot call. plt.xticks() and plt.yticks() change the marks on the axes.
Plotting straight from pandas
df.plot(kind='line', x='Month', y='Sales') df.plot(kind='bar', x='Subject', y='Marks') df['Marks'].plot(kind='hist', bins=5)
Saving plots
plt.savefig('sales.png') # PNG image in the current folder
plt.savefig('c:/charts/sales.pdf') # PDF, full path
plt.savefig('sales.jpg', dpi=150)Call savefig() before plt.show(). After show() closes, the figure is empty and you save a blank picture.
Try it: chart your week
Write down how many minutes you spend on your phone each day for 7 days. Make a line plot (days vs minutes) with a title, labels and savefig('week.png'). Then ask 10 friends their height in cm and draw a histogram with 4 bins. Before running, guess which bin will be tallest. In the 3D, step 6, switch bins between 2, 5 and 7 and notice how the shape changes.
Key formulas and definitions
- import matplotlib.pyplot as plt
- plt.plot(x, y) line ยท plt.bar(x, h) bar ยท plt.barh(y, w) ยท plt.hist(data, bins=n or list)
- plt.title() ยท plt.xlabel() ยท plt.ylabel() ยท plt.legend() (needs label=)
- plt.savefig('file.png') before plt.show()
- df.plot(kind='line' | 'bar' | 'hist')
Worked examples
1. Which chart suits (a) temperature over 7 days, (b) marks in 5 subjects, (c) heights of 40 students?
(a) line plot (change over time), (b) bar graph (separate groups), (c) histogram (spread of one number column).
2. Write code for a red dashed line plot of year [2021, 2022, 2023, 2024] against students [300, 340, 390, 420] with circle markers.
plt.plot([2021,2022,2023,2024], [300,340,390,420], color='r', linestyle='--', marker='o'); plt.show()
3. Draw a bar graph of fruits ['Apple','Mango','Banana'] sold [40, 65, 30] with title 'Fruit Sales' and axis labels.
plt.bar(['Apple','Mango','Banana'], [40,65,30]); plt.title('Fruit Sales'); plt.xlabel('Fruit'); plt.ylabel('Units sold'); plt.show()
4. marks = [35,42,48,51,55,58,61,63,66,68,72,74,79,85,93] with bins=[30,44,58,72,86,100]. Find the frequency of each bin.
30โ44: 35, 42 โ 2. 44โ58: 48, 51, 55 โ 3. 58โ72: 58, 61, 63, 66, 68 โ 5. 72โ86: 72, 74, 79, 85 โ 4. 86โ100: 93 โ 1. Total 15.
5. Plot sales of Shop A and Shop B on one chart with a legend and save it as 'compare.png'.
plt.plot(month, a, label='Shop A'); plt.plot(month, b, label='Shop B'); plt.legend(); plt.savefig('compare.png'); plt.show()
6. A student wrote plt.show() and then plt.savefig('x.png'). The file is blank. Why, and how to fix?
show() displays and then clears the figure, so savefig saved an empty figure. Put savefig() before show().
Common mistakes
- Using a bar graph for a continuous number column; a histogram is right when you want the spread in ranges.
- Calling plt.legend() without label= in the plot calls, so the legend box is empty.
- Saving after plt.show(), which saves a blank image.
- Thinking bins=5 counts 5 values; it makes 5 ranges and counts how many values fall in each.