Colormap in the background of a scatterplot in Python

Question:

I’d like to plot a colormap behind my scatterplot showing that as far as you go from the median value, the worst your parameter is. Something like the following image (but smoother and with a defined colormap):

Scatter plot with background

Here’s a MWE of what I used to plot the figure:

x = np.arange(0,11)
y = [3.03533424, 3.22326981, 3.05219723, 4.5, 3.21876807, 3.14124761, 3.43615915, 3.21650377, 3.2924148 , 3.30075672, 5.7]
plt.plot(x, y, marker='o', color='k')
plt.axhline(np.median(y), color='blue', label='Median')

It would be great if the resolution of the colormap was higher than the number of points I have so I get the smooth plot I expect.

Thanks in advance.

Asked By: VictorSalles

||

Answers:

How about using pcolormesh? This is very straight work around and there might be a cleverer way. The idea is to create a dummy data (triangular distribution in this example) that peaks at the median value and use it to plot color map by pcolormesh. The dummy data has the 2D shape of ( xdata-length, ydata-length ). It can be any distribution, gaussian for example.

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

res = 100 # data resolution
xdata = np.linspace(*np.random.randn(2), res) # random x data
ydata = np.random.randint(10,20)*xdata + np.random.rand(res)*10 # random data with noise and ramp

ymax, ymin = np.max(ydata), np.min(ydata) # get data range
median = (ymax + ymin) / 2.0
ydata_for_cmap = np.linspace(ymin, ymax, res) # y axis for cmap
zdata_for_cmap = np.hstack(
    [np.linspace(ymin, median, int(res/2)),
     np.linspace(median, ymin, int(res/2))] 
    ) # triangular shape function for cmap

zz, _  = np.meshgrid(zdata_for_cmap, zdata_for_cmap, indexing="ij")
yy, xx = np.meshgrid(ydata_for_cmap, xdata, indexing="ij")

fig, ax = plt.subplots(1,1,figsize=(9,6))
cmap=cm.viridis
ax.plot(xdata, ydata, "ko-")
ax.axhline(median)
ax.pcolormesh(xx, yy, zz, cmap=cmap)

It creates a figure like this.
figure

Answered By: atommy