"complex" plots with varying alpha values


I have several datapoints in space. I’m binning and taking the average and I’m trying to plot these in different ways: contourf, streamplot and quiver. But before plotting I am making and interpolation with LinearTriInterpolator.
However some bins are empty and with the interpolation these bins will magically have data and will be plotted. To make this distinction I thought of using alpha=1 for occupied bins and something else for vacant bins.

I managed to do this with scatterplots as follows:

import numpy as np
from matplotlib import cm
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt

color_array = np.array([1,2,3,4,5])

alpha_array = np.array([2,10,0,0,2], dtype=np.float32)
alpha_array[alpha_array != 0] = 1
alpha_array[np.isclose(alpha_array,0)] = 0.3

norm = Normalize(vmin=color_array.min(),
cmap = cm.get_cmap('viridis')

color_array = norm(color_array)
color_array = cmap(color_array)

color_array[...,-1] = alpha_array

plt.scatter([1,2,3,4,5], [1,2,3,4,5], c=color_array)

In this toy example I have 5 bins and alpha_array contains the occupation number of each bin and because of the normalization, the alphas will be [0.2, 1. , 0. , 0. , 0.2]

This works very nicely with scatterplots since I can pass “A 2D array in which the rows are RGB or RGBA.” but for the contourf, quiver and streamplot I can’t find this option. (and if I try to force it using the colors arguments on contourf for example, it complains because it’s not expecting RGB or RGBA)

Am I missing something? Is it possible to do it?

I am using ubuntu 20.04 LTS and matplotlib 3.4.1 on python 3.8

Thanks in advance

you definitely cannot do it directly for contourf and streamplot because those are interpolations themselves and don’t know or care about the underlying data grid once their artists are made. You could try pcolormesh instead of contour. quiver it may be possible to color each quiver with a different alpha. For all of the artists types, you could probably make a new pcolormesh that had alpha=0 for good bins and alpha=0.2 or something for empty bins and then overlay.

Thank for your reply. I’ll check that out.