How would you implement a cyclic interpolation method to be used with the matplotlib.pyplot.imshow function?
When the imshow-function is utilized for visualizing data with cyclical nature, such as the times of the 24 hour clock, the cyclical color maps are quite useful. However, if the imshow is used to upscale the data using interpolation, the plots don't come out as one would expect.
See below:
import numpy as np
import matplotlib.pyplot as plt
colormap = plt.cm.twilight_shifted
# Create an array with values between 0-3
arr = np.random.randint(0,4,size=[16,16])
# Create a smaller array with values between 20-23
patch = np.random.randint(20,24,size=[4,4])
# Insert the patch in the middle of the array
arr[6:10,6:10] = patch
# Visualize the array, without interpolation
plt.figure(figsize=[18,10])
plt.imshow(arr, cmap = colormap, aspect='auto', interpolation=None)
plt.colorbar()
# Visualize the array, with interpolation
plt.figure(figsize=[18,10])
plt.imshow(arr, cmap = colormap, aspect='auto', interpolation='bicubic')
plt.colorbar()
Results in two plots:
No interpolation Bicubic interpolation
You can see that the interpolation creates a white line between the two groups of values, corresponding to values around 12. However, since we are utilizing a cyclic color map, I would actually expect the values interpolated between the [0,3] and [20,23] groups to be black. I assume this is because the interpolation methods implemented in the imshow function don't account for the cyclicity of the color map.
Any ideas on how to achieve proper interpolation for the visualization? Should cyclic interpolation for cyclic colormaps be added to matplotlib as a feature?
A nice workaround is using interpolation_stage='rgba'. With that property set, the interpolation is done after the colors have been calculated. I don't think there are any downsides to this, except if your color maps have sharp jumps.
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html
import numpy as np
import matplotlib.pyplot as plt
colormap = plt.cm.twilight_shifted
X, Y = np.meshgrid(np.arange(16), np.arange(16))
arr = X % 8
fig, axes = plt.subplots(figsize=[30,10], dpi=300, ncols=3)
# no interpolation
axes[0].imshow(arr, cmap = colormap, aspect='auto', interpolation=None)
axes[0].set_title('No interpolation')
# bicubic
axes[1].imshow(arr, cmap=colormap, aspect='auto',
interpolation='bicubic'
)
axes[1].set_title('Bicubic interpolation')
# bicubic with color interpolation
ax_img = axes[2].imshow(arr, cmap=colormap, aspect='auto',
interpolation='bicubic', interpolation_stage='rgba'
)
axes[2].set_title('Bicubic color interpolation')
plt.colorbar(mappable=ax_img, ax=axes[2])

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With