Contents
Creating Charts with Matplotlib
Matplotlib supports several chart types. Choosing the right one depends on the question you want to answer.
Line Charts
Line charts are useful for showing trends over time or across an ordered sequence.
days = [1, 2, 3, 4, 5, 6]
website_visits = [120, 150, 135, 180, 210, 250]
plt.plot(days, website_visits, marker="o")
plt.title("Daily Website Visits")
plt.xlabel("Day")
plt.ylabel("Number of Visits")
plt.grid(True)
plt.show()
Markers highlight individual observations, while grid lines make values easier to compare.
Bar Charts
Bar charts compare values across distinct categories.
products = ["Laptop", "Phone", "Tablet"]
units_sold = [120, 250, 180]
plt.bar(products, units_sold)
plt.title("Product Sales Comparison")
plt.xlabel("Product")
plt.ylabel("Units Sold")
plt.show()
Bar charts are useful for comparing sales by product, revenue by region, or employees by department.
Histograms
Histograms show the distribution of numerical data by grouping values into intervals.
delivery_times = [20, 25, 30, 22, 35, 40, 28, 32, 45, 38, 27, 31]
plt.hist(delivery_times, bins=5, edgecolor="black")
plt.title("Distribution of Delivery Times")
plt.xlabel("Delivery Time (Minutes)")
plt.ylabel("Frequency")
plt.show()
A histogram helps reveal where observations are concentrated and whether the distribution is spread out or skewed.
Saving a Chart
Matplotlib allows charts to be saved as image files for reports and presentations.
plt.plot(months, sales)
plt.title("Monthly Sales")
plt.savefig("monthly_sales.png", dpi=300, bbox_inches="tight")
plt.show()
The dpi parameter controls image resolution, and bbox_inches="tight" helps prevent labels from being unnecessarily cropped. Save the figure before closing it.
Python for Data Science
Vishalini A








