When I started writing about Python programming for petrophysical measurements and well log data, most of my focus was on seeing what was possible with Matplotlib. Eventually, I found that creating the basic log plot was relatively straightforward. Curve tracks are essentially line plots with the axes swapped and the y-axis reversed.
Adding multiple tracks together to form a plot started to become much more of a fiddle, especially when trying to reduce spacing, getting the curve legends to behave and trying to add cross-over shading between a density curve on one scale, and neutron porosity on another.
After that came adding a track to display different lithologies.
Visually, it may look like the simplest part of the figure. After all it is just a column of colours against depth. But there are a few extra things we need to consider when we build one.
Matplotlib and Plotly are mainly designed around numerical data plotted against x and y axes. A facies track is slightly different.
Instead of continuous measurements, we normally have discrete classes such as shale, sandstone or limestone. Those classes need to be mapped to colours, plotted against depth and kept consistent between wells.
In this article, we will look at a few ways of doing this in Matplotlib and Plotly, along with some of the problems that can come up.
Creating Some Synthetic Data
For the examples in this article, we will use a synthetic dataset.
The aim here is not to create a realistic geological model. We just need some blocky facies intervals and a few curves whose values vary depending on the facies.
Each facies can then be assigned a typical gamma ray, bulk density and neutron porosity response.
import numpy as np
rng = np.random.default_rng(42)
step = 0.15
depth = np.arange(2000, 2200 + step, step)
facies_names = [”Shale”, “Silty Shale”, “Shaly Sand”, “Sandstone”, “Limestone”]
facies = np.empty(depth.size, dtype=int)
i = 0
while i < depth.size:
thickness = int(rng.uniform(2.0, 12.0) / step)
facies[i:i + thickness] = rng.choice([0, 1, 2, 3, 4])
i += thickness
# GR, RHOB and NPHI character per facies
character = {
0: (110, 2.55, 0.30), # Shale
1: (85, 2.50, 0.25), # Silty Shale
2: (60, 2.42, 0.20), # Shaly Sand
3: (28, 2.28, 0.14), # Sandstone
4: (18, 2.68, 0.04), # Limestone
}
We can use these values as the base response and add some smoothed random variation.
def curve(index, sd, smooth=9):
base = np.array([character[f][index] for f in facies], dtype=float)
noise = rng.normal(0, sd, base.size + smooth - 1)
return base + np.convolve(noise, np.ones(smooth) / smooth, mode=”valid”)
gr = np.clip(curve(0, 22), 0, 200)
rhob = np.clip(curve(1, 0.10), 1.9, 2.95)
nphi = np.clip(curve(2, 0.05), -0.05, 0.45)The result gives us three curves with enough variation to look like log data, while still keeping the facies changes visible.
Start With the Colour Key
Before plotting the facies track, we need to decide how each class will be represented. We can do this by creating a list of colours:
facies_colours = [”#4A5A48”, “#8B9B7A”, “#C9B072”, “#F2D06B”, “#7FA9D0”]The exact colours are less important than keeping the mapping consistent.
If sandstone is yellow in one well, it should still be yellow in the next.
This becomes important when one well does not contain all of the facies classes.
In Matplotlib, we can create a discrete colourmap using ListedColormap.
from matplotlib.colors import ListedColormap, BoundaryNorm
cmap = ListedColormap(facies_colours)
norm = BoundaryNorm(np.arange(-0.5, len(facies_colours) + 0.5), cmap.N)BoundaryNorm creates a separate interval around each integer facies code.
This means:
0 always maps to shale
1 always maps to silty shale
2 always maps to shaly sand
3 always maps to sandstone
4 always maps to limestone
Without this fixed mapping, Matplotlib can rescale the colourmap based on the classes that happen to be present.
This may not be obvious on a single plot. However, imagine one well contains classes 0 to 4 and another contains only classes 0 to 3. If the colour scale is automatically stretched across the available values, the same facies code can appear using a different colour.
That can make comparisons between wells more difficuly and potentially misleading.
Plotting the Facies Track
One option is to use fill_betweenx.
For each facies class, we fill the width of the track where that class occurs.
for code, colour in enumerate(facies_colours):
ax.fill_betweenx(depth, 0, 1, where=(facies == code), facecolor=colour)This can work, but it is not always ideal for every categorical data track.
fill_betweenx is designed to fill the area between numerical curves. When we use separate masks for facies intervals, small gaps can sometimes appear at class boundaries.
There are a few ways to deal with that.
Closing the Gaps
The smallest change is to expand each mask by one sample on either side.
for code, colour in enumerate(facies_colours):
mask = (facies == code)
mask = mask | np.roll(mask, 1) | np.roll(mask, -1)
ax.fill_betweenx(depth, 0, 1, where=mask, facecolor=colour)This removes most visible gaps on the plot, but it also introduces overlap between neighbouring classes.
Drawing order then determines which class occupies the boundary. np.roll also wraps around at the ends of the array, so the top and bottom samples need a little care when being applied.
A more direct approach is to identify each contiguous facies interval and draw it as a single span.
edges = np.flatnonzero(np.diff(facies)) + 1
starts = np.concatenate([[0], edges])
ends = np.concatenate([edges, [facies.size]])
for s, e in zip(starts, ends):
ax.axhspan(depth[s] - step / 2,
depth[e - 1] + step / 2,
facecolor=facies_colours[facies[s]])This is more code, but it gives us direct control over the position of each boundary.
The boundary is placed halfway between the samples on either side, which is a reasonable representation when the contact is only known to the sampling interval.
Another option is to stop treating the facies track as a collection of filled areas.
Instead, we can treat it as a one-column image.
ax.imshow(facies.reshape(-1, 1), aspect=”auto”, cmap=cmap, norm=norm,
extent=[0, 1, depth.max(), depth.min()], interpolation=”none”)For a simple full-well facies track, this is usually the approach I prefer.
It only requires one call, there are no gaps between layers and it scales well for long wells.
The extent sets the depth range and reverses the vertical direction.
The interpolation="none" setting is also important.
When an image contains more samples than there are screen pixels available, Matplotlib has to resample it. For continuous image data that may be useful. For categorical data it can create colours that do not represent any actual facies.
For example, a five-class facies track may contain dozens of slightly different colours after interpolation.
The visual effect can be subtle, particularly on screen, but there is no reason to introduce colours that have no geological meaning.
If I need direct control over individual intervals or contacts, I would use axhspan.
Putting the Tracks Together
Once the facies column is sorted, combining it with the log curves is mostly a layout problem.
Here we have three curve tracks and one narrow facies track, all sharing the same depth axis.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 4, figsize=(11, 9), sharey=True,
gridspec_kw={”width_ratios”: [1, 1, 1, 0.35]})
axes[0].plot(gr, depth, color=”#2C6E49”, lw=0.7); axes[0].set_xlim(0, 200)
axes[1].plot(rhob, depth, color=”#C1121F”, lw=0.7); axes[1].set_xlim(1.9, 2.9)
axes[2].plot(nphi, depth, color=”#0353A4”, lw=0.7); axes[2].set_xlim(0.45, -0.05)
axes[3].imshow(facies.reshape(-1, 1), aspect=”auto”, cmap=cmap, norm=norm,
extent=[0, 1, depth.max(), depth.min()], interpolation=”none”)
axes[3].set_xticks([])
axes[0].set_ylim(depth.max(), depth.min())
axes[0].set_ylabel(”Depth (m)”)
for ax in axes[:3]:
ax.grid(alpha=0.25)
ax.xaxis.set_label_position(”top”)
ax.xaxis.tick_top()There are a few small details here that make life easier.
Using sharey=True keeps all of the tracks aligned.
width_ratios lets us make the facies track narrower than the curve tracks.
I also prefer to reverse the depth axis once by setting the limits on the first shared axis rather than calling invert_yaxis() on every subplot.
A Blocked, Zero-Centred Track
A full-width facies track uses colour to represent the class.
But, we can also use width to represent it as well.
Instead of filling the whole track, each interval can be centred on zero with its width determined by the class.
This gives us something closer to a grain-size or energy style log.
half_width = {code: (code + 1) / n for code in range(n)}
for s, e in zip(starts, ends):
code = facies[s]
w = half_width[code]
ax.fill_betweenx([depth[s] - step / 2, depth[e - 1] + step / 2],
-w, w,
facecolor=facies_colours[code],
edgecolor=”black”, linewidth=0.4)
ax.set_xlim(-1.1, 1.1)The thin black edge is worth keeping to help prevent two adjacent layers of similar width and similar colour merge into one block.
If width represents an ordered property, we can also use a sequential colourmap so that colour and width change in the same direction.
base_cmap = plt.get_cmap(”viridis”)
facies_colours = [base_cmap(v) for v in np.linspace(0.1, 0.9, n)]
cmap = ListedColormap(facies_colours)I find this version is often easier to scan because changes in width create a recognisable profile. However, there is an important limitation.
Width can sometimes imply that there is an order.
If we assign widths directly from facies codes, we can inadvertently tell the reader that the classes form some kind of sequence.
That may make sense for certain scenarios such as grain size or reservoir quality then this can be very useful.
This is similar to label encoding a categorical variable before using it in a machine learning model. The numbers imply an order even when the classes themselves may not have one.
Building the Legend
Neither imshow nor the filled spans automatically create useful legend entries for a categorical facies track.
The easiest solution is to create proxy patches.
from matplotlib.patches import Patch
handles = [Patch(facecolor=c, label=n)
for c, n in zip(facies_colours, facies_names)]
fig.legend(handles=handles, loc=”lower center”, ncol=5, frameon=False)I prefer generating the legend directly from the same names and colours used by the plot.
That way, if the facies scheme changes, the plot and the legend change together.
Comparing Predicted and Actual
Facies tracks also become useful when comparing hand interpreted classes with a prediction from a classification machine learning model. Instead of looking only at a classification score, we can place the actual and predicted facies tracks next to each other.
We can then add another narrow track showing where they disagree.
The example below uses a synthetic prediction. It deliberately includes misplaced contacts, several incorrectly classified beds and some scattered disagreement between neighbouring classes.
It is only being used to illustrate the plot.
mismatch_cmap = ListedColormap([”#FFFFFF”, “#C1121F”])
for ax, data, label in [(axes[1], facies, “Actual”),
(axes[2], predicted, “Predicted”)]:
ax.imshow(data.reshape(-1, 1), aspect=”auto”, cmap=cmap, norm=norm,
extent=[0, 1, depth.max(), depth.min()], interpolation=”none”)
ax.set_xlabel(label)
axes[3].imshow((predicted != facies).astype(int).reshape(-1, 1), aspect=”auto”,
cmap=mismatch_cmap, vmin=0, vmax=1,
extent=[0, 1, depth.max(), depth.min()], interpolation=”none”)The mismatch track uses its own two-colour map so that disagreement cannot be mistaken for another facies class.
And vmin and vmax are pinned explicitly. Without that, Matplotlib may rescale the colours if only one of the two values happens to be present in the plotted interval.
The useful part of this plot is not simply seeing how often the prediction is wrong. It actually shows where it is wrong in terms of depth.
A thin mismatch around a contact is different from an entire bed being assigned to the wrong facies. In this synthetic example, the overall agreement is 75%. However, the number 75% on its own can tell us that 75% matched, but not where and how.
Most of the disagreement in this example is concentrated in only a few beds, while a smaller proportion comes from slightly misplaced boundaries.
If entire beds are being confused, I would start by looking at class separability and the input features available to the model. It may be the case that the log responses are fairly similar for these two groups and may need further investigation in order to find a way to separate them.
If most errors occur around contacts, then bed thickness, sampling rate and the uncertainty in the interpreted boundary may be more important.
A confusion matrix is still useful because it tells us which classes are being confused. What it cannot show is where those errors occur in the well.
For facies classification, I think having a confusion matrix, a depth plot and the key metrics are useful.
Plotly: The Same Idea
Plotly does not have a direct equivalent of using fill_betweenx with categorical masks. You could create a large number of rectangular shapes, but that quickly becomes cumbersome.
A one-column heatmap works better and is conceptually similar to the imshow approach in Matplotlib.
The main complication is the colour scale.
Plotly heatmaps use a continuous colourscale between 0 and 1.
To make it behave like a categorical palette, we can repeat each colour at the start and end of its section of the scale.
n = len(facies_colours)
colourscale = []
for k, colour in enumerate(facies_colours):
colourscale.append([k / n, colour])
colourscale.append([(k + 1) / n, colour])This creates flat colour bands instead of interpolating gradually between classes.
The facies track can then be added as a heatmap.
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=4, shared_yaxes=True,
horizontal_spacing=0.03,
column_widths=[1, 1, 1, 0.35],
subplot_titles=[”GR (API)”, “RHOB (g/cm3)”,
“NPHI (v/v)”, “Facies”])
fig.add_trace(go.Scatter(x=gr, y=depth, line=dict(color=”#2C6E49”, width=1)), 1, 1)
fig.add_trace(go.Scatter(x=rhob, y=depth, line=dict(color=”#C1121F”, width=1)), 1, 2)
fig.add_trace(go.Scatter(x=nphi, y=depth, line=dict(color=”#0353A4”, width=1)), 1, 3)
fig.add_trace(go.Heatmap(
z=facies.reshape(-1, 1), y=depth, x=[0],
colorscale=colourscale, zmin=-0.5, zmax=n - 0.5,
showscale=False,
text=np.array(facies_names)[facies].reshape(-1, 1),
hovertemplate=”%{y:.2f} m<br>%{text}<extra></extra>”,
), 1, 4)
fig.update_yaxes(autorange=”reversed”, row=1, col=1, title_text=”Depth (m)”)
fig.update_xaxes(range=[0.45, -0.05], row=1, col=3)Plotly makes some parts of this easier. For example, reversing the depth axis is simply autorange="reversed".
Where Plotly Helps
The main reason I would use Plotly here is interaction. Plotly makes it easy to see values when hovering over curves, zooming and changing data ranges.
By passing the facies name through text, the hover information can show both the depth and the facies class. This becomes handy when checking a classification result against the surrounding curves.
Instead of estimating the depth from the axis, you can move directly over the interval and see what the model has assigned.
There is a slight pain with the legend. A Plotly heatmap normally uses a continuous colourbar. That does not make much sense when the values are categorical facies codes.
We can turn the colourbar off with showscale=False, but then we have no key.
One workaround is to create empty traces purely for the legend.
for name, colour in zip(facies_names, facies_colours):
fig.add_trace(go.Bar(x=[None], y=[None], name=name,
marker=dict(color=colour), showlegend=True), 1, 1)
fig.update_layout(legend=dict(orientation=”h”, y=-0.08))It works, although it does feel like a workaround rather than something Plotly was specifically designed to do.
Which One to Reach For — Matplotlib or Plotly?
For static log plots, I still tend to favour Matplotlib, as anyone who has followed me for a while will know. Matplotlib gives you a lot of control over track widths, headers, legends and exported figures, which matters when the final plot is going into a report, paper or presentation.
Plotly becomes more interesting when the figure is something you want to explore or display on a dashboard. Hovering over individual intervals, zooming into part of the well and checking predicted facies against log responses all work naturally in an interactive plot.
There is also a separate decision about how the facies itself should be displayed.
A simple colour column works for any categorical facies scheme.
A blocked track that changes width can be easier to read, but only if the width represents something that really has an order.
Whichever approach we use, I think the most important part is keeping the facies mapping consistent.
The same class should always have the same colour.
Ideally, that mapping should be defined once alongside the facies scheme and then reused to create the Matplotlib colourmap, the legend and the Plotly colourscale.
Once that is in place, the plotting itself becomes much easier.
If you want to explore a few more ways of visualising data with Python, take a look at my article: 3 Python Charts You’re Probably Not Using (But Should Be).
It covers three less commonly used chart types and where they can be useful when standard plots are not quite showing you what you need.








