Data visualization is one of the most powerful communication tools in programming. It allows us to identify trends, outliers, and patterns that are invisible when looking at raw lists, arrays, or spreadsheets. In Python, the standard library for data visualization is Matplotlib.
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
For 90% of your plotting needs, you will use the matplotlib.pyplot submodule. Pyplot is a collection of functions that make Matplotlib work like MATLAB, enabling quick and easy plot generation.
Before using Matplotlib, install it:
pip install matplotlibBy convention, it is always imported as plt:
import matplotlib.pyplot as pltA line plot displays data as a series of data points connected by straight line segments. It is best used for tracking changes over continuous intervals (like time).
Let's write a simple script to plot temperature changes over a week.
Input:
import matplotlib.pyplot as plt
# Data
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
temperatures = [22, 24, 21, 25, 27, 26, 28]
# 1. Generate the line plot
plt.plot(days, temperatures)
# 2. Display the plot (opens a window or outputs inline in notebooks)
plt.show()A raw plot is rarely publication-ready. Pyplot allows you to easily customize:
color: The line color (e.g.'blue','r'for red, or hex codes like'#FF5733').linestyle: The style of the line (e.g.'-'solid,'--'dashed,':'dotted).marker: The symbol at each data point (e.g.'o'circle,'s'square,'^'triangle).linewidth: Thickness of the line.
Input:
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
temp = [22, 24, 21, 25, 27, 26, 28]
# Customizing style in plt.plot()
plt.plot(days, temp, color="red", linestyle="--", marker="o", linewidth=2)
plt.show()Adding context to your plots is crucial so that others can interpret the data without reading your code.
plt.title(): Adds a title at the top of the plot.plt.xlabel()/plt.ylabel(): Adds labels to the horizontal and vertical axes.plt.legend(): Adds a box identifying multiple lines (requires settinglabel="..."insideplt.plot()).plt.grid(True): Adds grid lines in the background.
Input:
import matplotlib.pyplot as plt
# Data for two cities
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
london_temp = [22, 24, 21, 25, 27, 26, 28]
paris_temp = [25, 23, 26, 28, 29, 30, 31]
# Plotting both lines with labels for the legend
plt.plot(days, london_temp, color="blue", marker="o", label="London")
plt.plot(days, paris_temp, color="orange", marker="s", linestyle="--", label="Paris")
# Adding descriptors
plt.title("Weekly Temperature Comparison")
plt.xlabel("Day of the Week")
plt.ylabel("Temperature (°C)")
# Enable legend, grid, and show the plot
plt.legend()
plt.grid(True)
plt.show()Instead of just showing the plot, you can save it directly as an image file (PNG, JPG, PDF) using plt.savefig('filename.ext').
Warning
Save Before Showing:
Always call plt.savefig() before calling plt.show(). Calling plt.show() clears the current figure buffer, resulting in a blank image if you try to save after it.
Input:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y, marker="x")
plt.title("Sample Plot")
# Saving plot to disk (dpi stands for dots per inch - controls resolution)
plt.savefig("sample_chart.png", dpi=300)
print("💾 Chart successfully saved as 'sample_chart.png'.")Output:
💾 Chart successfully saved as 'sample_chart.png'.