Plotting heat maps of scalar fields in SAGE

111 views
Skip to first unread message

Gaurish Telang

unread,
Oct 19, 2022, 5:18:37 AM10/19/22
to sage-support

I want to create heat maps of a scalar field in SAGE. Here is equivalent code in Matplotlib that does the job along with the resulting output. The matplotlib code uses the .pcolormesh function. Is there an equivalent in SAGE?

The closest I can see are the functions that create contour plots as given here, but I don’t want the discrete bands that are created in those plots; for contour plots that is of course natural because you want to see the shapes of the individual level curves.

However, I specifically want the continuous smearing as outputted by the Matplotlib code below, which gives a “heat-map” of the 2D scalar function.

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

fig,ax = plt.subplots()
L = 3
x    = np.linspace(-L, L, 100) 
y    = np.linspace(-L, L, 100) 
X, Y = np.meshgrid(x, y)
Z    = np.cos(X) - 2*Y 

z_min, z_max = -np.abs(Z).max(), np.abs(Z).max()
c= ax.pcolormesh(X, Y, Z, cmap='RdBu', vmin=z_min, vmax=z_max) 
fig.colorbar(c, ax=ax)

ax.set_aspect(1.0)
ax.set_title("Heat map of scalar field",fontsize=20)
fig.set_size_inches((10,10))
plt.show()



Thanks!

Gaurish

Emmanuel Charpentier

unread,
Oct 19, 2022, 10:29:36 AM10/19/22
to sage-support

That can be done in Sage in a variety of ways . Here’s one :

var("x, y")
L = 3
# Plotted function
f =lambda x,y:cos(x)-2*y
# Coloring
# Colormap
cm=colormaps["RdBu"]
# We have to scale the colormap :
# Range of values : possible shortcut via some analytical obviousnesses :
# cmin = f(-3, 3).n()
# cmax = f(0, -3)
# Being dum and computing on grid :
foo = [u for u in (-3,-2.97..3)]
Mesh = [[f(u, v) for v in foo] for u in foo]
cmin = min(flatten(Mesh))
cmax = max(flatten(Mesh)
crange = cmax-cmin
cf = lambda x, y: f(x, y)/crange
# Plot
parametric_plot3d(lambda x, y, z:[x, y, f(x, y)], (-3, 3), (-3, 3),
                  color=(cf, cm), aspect_ratio=[2, 2, 1])

It turns out that plot3d(f, (-3, 3), (-3, 3), color=(cf, cm), aspect_ratio=[2, 2, 1]) also works, but the color= parameter is not documented as such for plot3d, only for parametric_plot3d.

You may also try to play with list_plot3d, which I do not use as often. Lazy me…

HTH,

Gaurish Telang

unread,
Nov 14, 2022, 9:47:27 AM11/14/22
to sage-support
Thanks so much! 
Reply all
Reply to author
Forward
0 new messages