It’s no secret that matplotlib’s defaults are functional, but they don’t always do the data justice! I have talked about this multiple times on here and over on Substack.
You’ll get a chart with the right data, the right axes, and roughly the right shape. But functional and clear aren’t the same thing, and the distance between them is mostly a handful of lines of code and personal choices.
This article covers six of them. They are not clever hacks, instead they are small adjustments that can become automatic once you’ve made them a few times.
The example I am using here is synthetic porosity-permeability scatter for four lithology types: Sand A, Sand B, Shaly Sand, and Tight Zone. Whilst this article is geoscience focused, the same changes can be applied to any chart to take them from matplotlib basic to something that you can easily put in a report.
Setting Up the Basic Matplotlib Plot
The starting point is a plain scatter with no styling decisions at all.
fig, ax = plt.subplots()
for formation, group in df.groupby(”Formation”):
ax.scatter(group[”Porosity”], group[”Permeability”], label=formation)
ax.set_xlabel(”Porosity (v/v)”)
ax.set_ylabel(”Permeability (mD)”)
ax.set_title(”Porosity vs Permeability by Formation”)
ax.legend()When we run the above, we get back the following, yet familiar matplotlib chart:
The raw matplotlib default — a working chart, but noisy and harder to read than it needs to b
It works. The data is there. But it’s also cluttered, visually heavy, and hard to focus on. The full box draws the eye away from the data. The colours fight each other. The axes don’t reflect the structure of the data. Five changes fix most of this.
1. Remove the box
The default figure comes with a full box. Four spines, equal weight, none of it called for by the data. Often, these extra elements are referred to as “Chart Junk”.
Removing the top and right spines immediately reduces the visual noise. Softening the remaining two drops their weight without losing the reference they give the reader.
ax.spines[”top”].set_visible(False)
ax.spines[”right”].set_visible(False)
ax.spines[”left”].set_color(”#aaaaaa”)
ax.spines[”bottom”].set_color(”#aaaaaa”)Depending on the chart and what you are trying to get across to your readers, it can sometimes be beneficial to add gridlines, however, adding them should not detract the eye from the data.
In this data example, we are going to be dealing with a logarithmic Y-axis later on, so it will be helpful to have that horizontal reference line. I often find that the horizontal grid lines lets the eyes read permeability values without having to mentally extend a line across the full chart. I also feel that the the vertical grid mostly adds noise.
We can turn the grid on for the Y-axis as follows.
ax.yaxis.grid(True, color=”#ebebeb”, linewidth=0.8, zorder=0)
ax.xaxis.grid(False)
ax.set_axisbelow(True)set_axisbelow(True) keeps the grid behind the data points. This may sound obvious, but by default matplotlib will draw the axis on top of the data, which can look messy.

Before and after removing the box and subduing the grid.
After applying the change, the difference is immediate and the data is easier to look at and interpret.
2. Use an intentional colour palette
Matplotlib’s default colour cycle isn’t bad. It wasn’t designed for any particular data structure though, so it assigns similar visual weight to every group regardless of what you’re trying to say.
Picking a palette deliberately forces a useful question: what do these groups mean relative to each other, and does the colour scheme reflect that?
Okabe-Ito is one solid starting point, but the right palette for your project depends on the data type, the audience, and how the chart will be reproduced. I’ve covered four tools on Substack that make that selection process significantly easier. Link at the end.
In this example, we have four different lithologies which have a rough quality order. Sand A and Sand B are the better reservoir rock. Shaly Sand and Tight Zone sit towards the the lower end.
A palette that groups the two sandy formations together and distinguishes the lower-quality ones makes that structure readable without any additional explanation.
The Okabe-Ito palette is a good starting point. It’s colour-blind safe and holds up across screens and print conditions. However, this is not the only palette available, and i would suggest that you explore other options to suit your needs.
PALETTE = {
“Sand A”: “#56B4E9”, # sky blue
“Sand B”: “#CC79A7”, # reddish purple
“Shaly Sand”: “#E69F00”, # golden amber
“Tight Zone”: “#D55E00”, # vermillion
}Two blues for the sands, amber and vermillion for the lower-quality formations. This provides a distinct change without being garish, and it can also avoid the red-green pairing that disappears for about 8% of readers.
for formation, group in df.groupby(”Formation”):
ax.scatter(
group[”Porosity”], group[”Permeability”],
label=formation,
color=PALETTE[formation],
s=45, alpha=0.80, edgecolors=”none”
)
Default colour cycle versus the Okabe-Ito palette
Colour is one of the fastest channels the eye processes. A palette that does nothing to support the data structure is a missed opportunity.
This is not to say the above palette is the one everyone should use, but being aware of colour blindness is something that is key to creating accessible data visualisations.
3. Fix the axes
Permeability spans orders of magnitude in most subsurface datasets. The difference between a tight formation and a productive sand isn’t a linear step, and plotting it that way compresses the variation that actually matters into a small portion of the chart.
A log-scale y-axis is often more appropriate. For this kind of data, it’s usually much clearer, and can be done with a one liner:
ax.set_yscale(”log”)Once the scale is right, the tick labels need attention. Matplotlib’s default log formatter tends to produce scientific notation or inconsistent formats depending on the range. For permeability in the 1 to a few thousand millidarcy range, plain whole numbers are easier to read.
ax.yaxis.set_major_locator(ticker.LogLocator(base=10, numticks=10))
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: f”{int(x):,}”))The y-axis limits are worth setting explicitly too. Matplotlib’s automatic limits leave outermost data points at the very edge of the plot area. Extending to the next power of 10 above the data maximum gives the chart some room without arbitrary padding.
import math
perm_max = df[”Permeability”].max()
top = 10 ** math.ceil(math.log10(perm_max))
ax.set_ylim(bottom=0.5, top=top)
Linear scale with default limits versus log scale with whole-number ticks and extended y-axis
This one tends to produce the biggest visible shift. On the linear scale, Sand A’s higher-permeability tail gets stretched out and the lower formations get squashed together. On log scale, the spread within each group is actually readable.
4. Add minor gridlines
Now, this may sound counter-intuitive to “removing the clutter” from a chart, However, when working with logarithmic scaled data I find that just having the major gridlines on the plot can cause issues for interpreting the values correctly.
Major gridlines on a log-scale axis sit at 1, 10, 100, 1,000. That’s useful, but it leaves a lot of unguided space in between. A value sitting between 10 and 100 could be anywhere from 11 to 99 without more reference. Minor gridlines fill those gaps at 2, 3, 4, 5, 6, 7, 8, and 9 within each decade.
The trick is keeping them light enough that they don’t compete with the data or the major gridlines. A dotted line in a near-white grey does the job.
ax.yaxis.set_minor_locator(ticker.LogLocator(base=10, subs=np.arange(2, 10) * 0.1, numticks=100))
ax.yaxis.grid(True, which=”minor”, color=”#f0f0f0”, linewidth=0.5, linestyle=”:”)subs=np.arange(2, 10) * 0.1 places minor ticks at the nine intermediate positions within each decade. The dotted style and near-white colour keep them clearly subordinate to the solid major gridlines.

Log-scale axis without and with minor gridlines. You may need to expand the image to see the changes.
The minor gridlines don’t change what the chart says, they help make it easier to read a value off the y-axis without guessing.
5. Annotate the insight
If there’s something specific the figure is supposed to communicate, it’s worth saying it. Readers can draw their own conclusions from an unlabelled chart, but not always the same one.
Annotations don’t need to be elaborate, but a short label and an arrow pointing at the relevant part of the data usually does it.
ax.annotate(
“Higher-quality reservoir\n(Sand A cluster)”,
xy=(0.272, 18),
xytext=(0.125, 150),
fontsize=9.5,
color=PALETTE[”Sand A”],
arrowprops=dict(arrowstyle=”->”, color=PALETTE[”Sand A”], lw=1.3),
va=”center”,
)Matching the annotation colour to the relevant group ties the label to the data visually, without needing a separate callout or legend entry.
It’s easy to skip this one. The chart looks finished before the annotation goes in. But there’s a difference between a chart that shows data and one that says something about it, and this is usually where that gap gets closed.
6. Finish the figure before exporting
Two settings that are easy to overlook: layout and resolution.
constrained_layout=True handles spacing between plot elements automatically. It’s more reliable than tight_layout() and avoids the common situation where an axis label gets clipped or a legend drifts over the plot area.
fig, ax = plt.subplots(figsize=(8, 5.5), constrained_layout=True)Resolution matters for anything going outside a Jupyter notebook. 150 dpi is fine for quick review. For a Medium article, a report, or a slide, 300 dpi is the sensible default. The file size is larger, but the output holds up at any zoom.
fig.savefig(”output_figure.png”, dpi=300, bbox_inches=”tight”)These aren’t visual changes in the way the earlier steps are. They’re finishing work. The kind that becomes obvious in hindsight when you export a figure and notice the labels are cut off or the text looks soft.
Putting it together
Here’s the full figure with all changes applied.
The complete code is below, with a helper function to keep the styling consistent across figures.
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# ── Synthetic dataset
np.random.seed(42)
n = 80
formations_params = {
“Sand A”: {”phi_mean”: 0.26, “phi_std”: 0.025, “perm_mu”: 2.4, “perm_sigma”: 0.35},
“Sand B”: {”phi_mean”: 0.20, “phi_std”: 0.020, “perm_mu”: 1.8, “perm_sigma”: 0.30},
“Shaly Sand”: {”phi_mean”: 0.18, “phi_std”: 0.020, “perm_mu”: 1.2, “perm_sigma”: 0.28},
“Tight Zone”: {”phi_mean”: 0.10, “phi_std”: 0.015, “perm_mu”: 0.3, “perm_sigma”: 0.20},
}
frames = []
for name, p in formations_params.items():
phi = np.clip(np.random.normal(p[”phi_mean”], p[”phi_std”], n), 0.04, 0.35)
perm = np.random.lognormal(p[”perm_mu”], p[”perm_sigma”], n)
frames.append(pd.DataFrame({”Formation”: name, “Porosity”: phi, “Permeability”: perm}))
df = pd.concat(frames, ignore_index=True)
# ── Palette
PALETTE = {
“Sand A”: “#56B4E9”, # sky blue
“Sand B”: “#CC79A7”, # reddish purple
“Shaly Sand”: “#E69F00”, # golden amber
“Tight Zone”: “#D55E00”, # vermillion
}
def apply_clean_style(ax, yscale=”linear”):
ax.set_facecolor(”white”)
ax.spines[”top”].set_visible(False)
ax.spines[”right”].set_visible(False)
ax.spines[”left”].set_color(”#aaaaaa”)
ax.spines[”bottom”].set_color(”#aaaaaa”)
ax.yaxis.grid(True, color=”#ebebeb”, linewidth=0.8, zorder=0)
ax.xaxis.grid(False)
ax.set_axisbelow(True)
ax.tick_params(axis=”both”, colors=”#555555”, length=3, width=0.8)
if yscale == “log”:
ax.set_yscale(”log”)
fig, ax = plt.subplots(figsize=(8, 5.5), constrained_layout=True)
fig.patch.set_facecolor(”white”)
for formation, group in df.groupby(”Formation”):
ax.scatter(
group[”Porosity”], group[”Permeability”],
label=formation,
color=PALETTE[formation],
s=50, alpha=0.82, edgecolors=”none”
)
apply_clean_style(ax, yscale=”log”)
perm_max = df[”Permeability”].max()
top = 10 ** math.ceil(math.log10(perm_max))
ax.set_ylim(bottom=0.5, top=top)
ax.yaxis.set_major_locator(ticker.LogLocator(base=10, numticks=10))
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: f”{int(x):,}”))
ax.yaxis.set_minor_locator(ticker.LogLocator(base=10, subs=np.arange(2, 10) * 0.1, numticks=100))
ax.yaxis.grid(True, which=”minor”, color=”#ebebeb”, linewidth=0.7, linestyle=”:”)
ax.set_xlabel(”Porosity (v/v)”, labelpad=10)
ax.set_ylabel(”Permeability (mD)”, labelpad=10)
ax.set_title(”Porosity vs Permeability by Formation”, pad=14)
ax.set_xlim(0.03, 0.35)
ax.annotate(
“Reservoir quality trend”,
xy=(0.265, 50),
xytext=(0.068, 10),
fontsize=9.5,
color=”#555555”,
rotation=0,
arrowprops=dict(arrowstyle=”->”, color=”#555555”, lw=1.3),
va=”center”,
ha=”left”,
)
ax.legend(title=”Formation”, title_fontsize=9, fontsize=9,
frameon=True, framealpha=0.95, edgecolor=”#dddddd”,
loc=”lower right”)
fig.savefig(”porosity_permeability.png”, dpi=300, bbox_inches=”tight”)None of these changes are complicated. Each one takes a few lines. The combined effect is a figure that’s easier to read, more honest about the data structure, and clearly finished rather than produced by default.
The defaults exist for good reasons. They get you to a working chart quickly without any configuration. But “working” is a low bar, and clearing it is not the same as making something that communicates well.
Choosing Okabe-Ito for this example wasn’t arbitrary. It came down to accessibility, contrast, and whether the colours would hold up across screens and print. For your own projects, those same questions apply, and the answer won’t always be the same palette. Check out the following article to find four tools that help when selecting a colour palette.
→ 4 Essential Tools to Help You Select a Colour Palette for Your Data Visualisation




