Set backgroundcolor of a Polar Plot using Colormaps

Viewed 344

I created a polar plot with matplotlib. Additionally, I have a value that lays between 0 and 3. The value should determine the background color I set the color of the plot now like:

    if 0.8 < x and x < 1.2:
            color = 'white'
    elif 1.2 < x and x < 1.4:
            color = 'white'

etc...
and later:

ax.set_facecolor(color)

However, that's not very convenient. My goal is that the color is white when its value is 1. For a value below 1, blue and for above 1, red. But continuously changing. Something like this gradient:

enter image description here

1 Answers

You could use the 'bwr_r' colormap (it is the reversed version of 'bwr'). A colormap gets a parameter between 0 and 1. 0 is mapped to the lowest color (red for 'bwr_r'), 0.5 is mapped to the middle color (white) and 1 to the highest color.

If your value of 0 needs to map to red and 1 to white, dividing the value by 2 puts it in the correct range. For values between 1 and 3, one could subtract 1, divide by 4 and add 0.5 to the result to map these values to the colors from white to blue. So, the code could look like ax.set_facecolor(plt.cm.bwr_r(val / 2 if val <= 1 else 0.5 + (val - 1) / 4)).

Alternatively, a TwoSlopeNorm does these calculations in a friendlier way via TwoSlopeNorm(vcenter=1, vmin=0, vmax=3). If you would like the reds and the blues less saturated, change it to TwoSlopeNorm(vcenter=1, vmin=-1, vmax=5).

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import TwoSlopeNorm

norm = TwoSlopeNorm(vcenter=1, vmin=0, vmax=3)
fig, axes = plt.subplots(ncols=6, nrows=2, figsize=(12, 5),
                         subplot_kw={'projection': 'polar'}, gridspec_kw={'hspace': 0.2, 'wspace': 0.25})
for i, ax in enumerate(np.ravel(axes)):
    val = i / 4
    ax.set_title(f'val = {val}')
    ax.set_facecolor(plt.cm.bwr_r(norm(val)))
    ax.set_xticklabels([])
    ax.set_yticklabels([])
plt.tight_layout()
plt.show()

resulting plot

Related