How to change contour color to white outside contour range using plotly?
I am using below to plot contour, I’d like to set color the white(not shown) if value is outside contour range like below z_min. For my plot, everything below z_min is still same color of blue color as zmin. I saw it is working from the below website example after setting start=, end= inside contour=dict(). Thanks for your help.
https://plotly.com/python/contour-plots/
fig.add_trace(go.Contour(
# last column, either pressure or temperature
z = Z.T,
x = X[:,0],
y = Y[0],
colorscale='Jet',
contours=dict(
start=z_min,
end=z_max,
size=25,
coloring="heatmap"),
zmin=z_min,
zmax=z_max
)
)
At the moment I can't think of any direct way to make the contour white.
One possible solution could be to replace any values outside of the contour range in your array with np.nan
before passing the array to the parameter z
in go.Contour
.
The NaN values in the array won't render and will appear transparent, meaning the tickmark lines and background can be seen. Then you can set the paper and plot background to be white so that the NaN values appear white.
Here is an example of how that can be accomplished. The larger the dimensions of the array you are plotting, the smoother the contours will be. In this 101 x 101
array, the change from the contour to the white background is not perfect, but pretty smooth.
import numpy as np
import plotly.graph_objects as go
x = np.linspace(0, 5, 101)
y = np.linspace(0, 5, 101)
xx, yy = np.meshgrid(x, y)
zz = (xx**2 + yy**2)
z_min, z_max = 10,50
zz_array_masked = zz.copy()
zz_array_masked[zz_array_masked < z_min] = np.nan
fig = go.Figure(data =
go.Contour(
z=zz_array_masked,
colorscale='Jet',
contours=dict(
start=z_min,
end=z_max,
size=1,
),
zmin=z_min,
zmax=z_max
))
fig.update_layout(
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)'
)
fig.show()