Complete guide to Matplotlib: from scratch to advanced plots

Share

Complete guide to Matplotlib: from scratch to advanced plots
Photo via editor Chatgpt

Data visualization may seem like an attempt to sketch the masterpiece with a lifeless pencil. You know what you want to create, but the tool in your hand just doesn’t work. If you’ve ever stared at the divine code, the tendency of the Matplotlib chart to make it look less like a messy way, you are not alone.

I remember when I used MatpLotlib for the first time. I had to delete the temperature data for the project, and after Googling Hours “how to rotate the X axis labels”, I finished with a chart that looked like he survived Tornado. Sounds familiar? That is why I prepared this guide – to aid you skip the frustration and start creating neat, professional plots that make sense.

Why matplotlib? (And why sometimes it seems awkward)

Matplotlib is Python’s grandfather who is planning libraries. He is powerful, elastic and … say, bizarre. Beginners often ask questions such as:

  • “Why does something as simple as a belt chart require 10 code lines?”
  • “How to stop your plot from looking, as if they were from 1995?”
  • “Is there a way to do it less painful?”

A low answer to them? Yes.

Matplotlib has a learning curve, but after understanding its logic you will unlock the endless adaptation. Think about how to teach the stick change: initially awkward, but you will soon change running without thinking.

First steps: Your first story in 5 minutes

Before we delve into advanced tricks, let’s nail the basics. Install Matplotlib With pip install matplotlibTry it.

The first thing to do: import matplotlib in a conventional way.

import matplotlib.pyplot as plt

Let’s create examples of data:

years = [2010, 2015, 2020]
sales = [100, 250, 400]

Now let’s create a figure and axis:

Time to delete the data:

ax.plot(years, sales, marker="o", linestyle="--", color="green")

Now add labels and title:

ax.set_xlabel('Year')
ax.set_ylabel('Sales (in thousands)')
ax.set_title('Company Growth: 2010-2020')

Finally, we need to display the plot:

What’s going on here?

  • plt.subplots() creates a figure (canvas) and axis (chart area)
  • ax.plot() Draws a linear chart. Marker, linear style and color arguments are jazz it up
  • Labels and titles are added from set_xlabel()IN set_ylabel()AND set_title()

For tips: Always mark your axles! Flated plot causes confusion and seems unprofessional.

Anatomy of the Matplotlib chart

To master Matplotlib, you must speak his language. Here is the division of key elements:

  • Figure: whole window or page. It’s a substantial picture.
  • Axes: where the chart happens. The figure can have many axes (think threads).
  • Axis: Xiy line, which define data limits.
  • Artist: Everything you see, from text, to lines, to markers.

Confused Figures vs. axes? Imagine the figure as a frame and axle frame as a photo inside.

Next steps

Ok, it’s time to make a plate … less ugly. The default style of matplotlib screams “academic paper from 2003” let’s get it. Here are some strategies.

1. Exploit style sheets

Style sheets are pre -configured pallets that bring consistent colors to work:

Other options that you can exploit to configure the color of the style sheet seabornIN fivethirtyeightIN dark_background.

2. Adjust the colors and fonts

Do not settle for default colors or fonts, add personalization. It doesn’t require much:

ax.plot(years, sales, color="#2ecc71", linewidth=2.5)
ax.set_xlabel('Year', fontsize=12, fontfamily='Arial')

3. Add nets (but sparingly)

You do not want the nets to become overwhelming, but adding them, when it is justified, can bring a specific style and usefulness to work:

ax.grid(True, linestyle="--", alpha=0.6) 

4. Key -related points

Is there any data point that requires an additional explanation? Admit: if necessary:

ax.annotate('Record Sales in 2020!', xy=(2020, 400), xytext=(2018, 350),
    arrowprops=dict(facecolor="black", shrink=0.05))

Equalization: Advanced techniques

1. Podplot: multitasking for charts

If you want to display many charts side by side, exploit threads below to create 2 poems and 1 column.

fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(8, 6)) axes[0].plot(years, sales, color="blue")  
axes[1].scatter(years, sales, color="red")  
plt.tight_layout()

The last line prevents overlapping.

2. Heat maps and contour charts

Visualize 3D data in 2D:

import numpy as np

x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

contour = ax.contourf(X, Y, Z, cmap='viridis')

If you want to add the color scale:

3. Interactive plots

Time for your charts to be clickable with mplcursors:

import mplcursors

line, = ax.plot(years, sales)
mplcursors.cursor(line).connect("add", lambda sel: sel.annotation.set_text(f"Sales: ${sel.target[1]}k"))

Wrapping

Before we get out of here, let’s take a look at Matplotlib’s joint headaches and their corrections:

  • “My labels are cut off!” – exploit plt.tight_layout() Or adjust the lining with Fig.
  • “Why is my plot empty?!” – I forgot plt.show() Using Jupyter? To add %matplotlib built at the top
  • “Fonts look pixel” – Save vector formats (PDF, SVG) with plt.savefig('plot.pdf', dpi=300)

If you are ready to experiment yourself, here are some challenges that you should complete now. If you get stuck, share your code in the comments and solve the problem.

  • Adjust the histogram matching the colors of your company brand
  • Recreate the chart from the latest news article best
  • Animate a chart showing data changes over time (Tip: Try FuncAnimation)

Finally, Matplotlib is evolving, just like your knowledge. Add these resources to check as progressed:

Application

Matplotlib is not only a library – it is a set of tools for telling stories. Regardless of whether you are visualizing climate data or planning sales trends, the goal is transparency. Remember that even Google experts “how to add a second y”. The key is to start a basic, often iteration and do not worry about documentation.

Shitttu chemive He is a software engineer and a technical writer, passionate about the exploit of the latest technologies to create attractive narratives, with a piercing eye to details and talent to simplify sophisticated concepts. You can also find shitttu on Twitter.

Latest Posts

More News