Python for Data & Web
Python Matplotlib Basics
Matplotlib is Python's most widely used charting library, letting you turn raw numbers into line plots, bar charts, and scatter plots with just a few lines of code.
The pyplot Module
Most beginner work uses matplotlib.pyplot, usually imported as plt. It offers simple functions to build a chart step by step: plot the data, add labels, then display or save the result.
pip install matplotlibLine Plot
A line plot is great for showing a trend over time, such as sales by month or temperature by day.
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [200, 240, 210, 300]
plt.plot(months, sales)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales (in units)")
plt.show()Bar and Scatter Plots
Use plt.bar() to compare values across categories, like scores of different students, and plt.scatter() to show the relationship between two numeric variables, like hours studied versus marks scored.
import matplotlib.pyplot as plt
students = ["Aarav", "Diya", "Kabir"]
scores = [78, 92, 85]
plt.bar(students, scores)
plt.title("Test Scores")
plt.show()import matplotlib.pyplot as plt
hours = [1, 2, 3, 4, 5]
marks = [40, 50, 55, 70, 90]
plt.scatter(hours, marks)
plt.xlabel("Hours Studied")
plt.ylabel("Marks")
plt.title("Study Hours vs Marks")
plt.show()Showing and Saving a Chart
plt.show() opens a window (or renders inline in a notebook) to display the chart. To save it as an image file for a report or presentation instead, use plt.savefig() before or instead of plt.show().
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 15])
plt.title("Example Chart")
plt.savefig("chart.png")Always add a title and axis labels — an unlabelled chart is confusing even if the data behind it is correct.
