Menu

Getting Started with Matplotlib

Getting Started with Matplotlib

Matplotlib is the most widely used plotting library in Python. Many other tools are built on top of it, so learning it gives you a strong base. This topic covers how it works and how to customize your first plots.

a. Understanding Figures and Axes

In Matplotlib, a figure is the whole canvas, like a blank sheet of paper. An axes is the area inside the figure where the data is actually drawn. One figure can hold one or many axes.

There are two ways to use Matplotlib. The simple way uses plt.plot() directly. The more flexible way creates the figure and axes first, and then draws on them.

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(months, sales)
plt.show()

The second style is called the object-oriented approach. It gives you better control and is the preferred style for anything beyond a quick plot.

b. Creating a Basic Line Plot

A line plot connects data points with a line. Pass the x values and the y values to the plot() method. It is the simplest and most common chart for showing change over time.

fig, ax = plt.subplots()
ax.plot(months, sales)
ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
plt.show()

Always add a title and axis labels. They tell the viewer what the chart shows and what the numbers mean. A chart without labels is hard to trust.

You can plot more than one line on the same axes by calling plot() again. Add a label to each line and call ax.legend() to show which is which.

c. Customizing Colors, Markers, and Line Styles

Small style changes can make a chart clearer. You can change the color, line style, line width, and add markers to show each data point.

ax.plot(months, sales, color="green", linestyle="--", linewidth=2, marker="o")

Colors can be named, like "blue", or written as hex codes, like "#1f77b4". Common line styles are "-" for solid, "--" for dashed, and ":" for dotted.

Do not overdo it. Use color and style to guide attention, not to decorate. When comparing several lines, make them different enough to tell apart, and keep the design consistent.

d. Saving Your Charts as Images

Once your chart looks right, you can save it as an image to use in reports or slides. Use the savefig() method before plt.show().

plt.savefig("monthly_sales.png", dpi=300, bbox_inches="tight")

The dpi setting controls the quality. A value of 300 gives a sharp image suitable for print. The bbox_inches="tight" option trims extra white space around the chart.

You can save in other formats too. PNG is common for web and slides, PDF and SVG are good for print and for charts that must stay sharp at any size.


Data Visualization Tutorial

WR

Wesline Rinisha



Learn via Video Course

Data Visualization Using Python Logo

Data Visualization Using Python

19 hrs



Get in Touch For Details