Visualization#
Using cyclic colormaps#
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from quantify_core.visualization.mpl_plotting import set_cyclic_colormap
zvals = xr.DataArray(np.random.rand(6, 10) * 360)
zvals.attrs["units"] = "deg"
zvals.plot()
<matplotlib.collections.QuadMesh at 0x7f937a192250>
![../_images/d593f38e54227979be80e67b8ea93aaf1121c78e4a7add6f92ef5514122a13d6.png](../_images/d593f38e54227979be80e67b8ea93aaf1121c78e4a7add6f92ef5514122a13d6.png)
fig, ax = plt.subplots(1, 1)
color_plot = zvals.plot(ax=ax)
set_cyclic_colormap(color_plot)
![../_images/794138dbb0c474a722c19d2593094b277bd218b6bc6983b58f0b89db90105a69.png](../_images/794138dbb0c474a722c19d2593094b277bd218b6bc6983b58f0b89db90105a69.png)
zvals_shifted = zvals - 180
fig, ax = plt.subplots(1, 1)
color_plot = zvals_shifted.plot(ax=ax)
ax.set_title("Shifted cyclic colormap")
set_cyclic_colormap(color_plot, shifted=zvals_shifted.min() < 0)
![../_images/b1a9f2837d48ecb889d55fec96a975ccd1a8b6ff42f9687c15a468829b715b94.png](../_images/b1a9f2837d48ecb889d55fec96a975ccd1a8b6ff42f9687c15a468829b715b94.png)
fig, ax = plt.subplots(1, 1)
color_plot = (zvals / 2).plot(ax=ax)
ax.set_title("Overwrite clim")
set_cyclic_colormap(color_plot, clim=(0, 180), unit="deg")
![../_images/f8b8bf5d8b767257563ff6d8632e6913874dee887fa32932e7a91c31ed3eea1b.png](../_images/f8b8bf5d8b767257563ff6d8632e6913874dee887fa32932e7a91c31ed3eea1b.png)
fig, ax = plt.subplots(1, 1)
zvals_rad = zvals / 180 * np.pi
zvals_rad.attrs["units"] = "rad"
color_plot = zvals_rad.plot(ax=ax)
ax.set_title("Radians")
set_cyclic_colormap(color_plot, unit=zvals_rad.units)
![../_images/a97539ae059ee60cf1df9ee15187bf9d8189462ac663d6638ba458c5082f4ea8.png](../_images/a97539ae059ee60cf1df9ee15187bf9d8189462ac663d6638ba458c5082f4ea8.png)
Creating custom colormaps#
In this example we use this function to create a custom colormap using several base colors for which we adjust the saturation and transparency (alpha, only visible when exporting the image).
import colorsys
import matplotlib.colors as mplc
import matplotlib.pyplot as plt
import numpy as np
from quantify_core.visualization.color_utilities import set_hlsa
color_cycle = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728"]
all_colors = []
for col in color_cycle:
hls = colorsys.rgb_to_hls(*mplc.to_rgb(mplc.to_rgb(col)))
sat_vals = (np.linspace(0.0, 1.0, 20) ** 2) * hls[2]
alpha_vals = np.linspace(0.4, 1.0, 20)
colors = [
list(set_hlsa(col, s=s)) for s, a in zip(sat_vals, alpha_vals)
]
all_colors += colors
cmap = mplc.ListedColormap(all_colors)
np.random.seed(19680801)
data = np.random.randn(30, 30)
fig, ax = plt.subplots(1, 1, figsize=(6, 3), constrained_layout=True)
psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
fig.colorbar(psm, ax=ax)
plt.show()
![../_images/13e837e5c6a255104650c8a7c8929d2e9c35afe481867bb8aafd55c5dfe4a289.png](../_images/13e837e5c6a255104650c8a7c8929d2e9c35afe481867bb8aafd55c5dfe4a289.png)