Feeds:
Posts

## Contour Plot in Sage and Matplotlib

Today I was playing around with Matplotlib and Sage(math) for plotting the relativistic addition of velocities.

First I tried the classic 3-dimensional plot in Sage,

var(‘x,y’)
p = plot3d((x+y)/(1+x*y), (x,0,.99), (y,0,.99), color=hue(0.8))
p.save(‘Vel-3d.png’)

Plot in 3D of velocities addition

However the plot was not so enlighten. So I tried a contour plot,

var(‘x’)
p = contour_plot((x+y)/(1+x*y), (x,0,.99), (y,0,.99), contours=[0.3,0.2,.5,.7,.9,.99], cmap=’hsv’, labels=True, fill=False,  fontsize=14)
fig = p.matplotlib(axes_labels=[‘$V/c$’,’$v/c$’])
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig.set_canvas(FigureCanvasAgg(fig))
axes = fig.get_axes()[0]
axes.minorticks_off()
axes.set_xticks([float(j/10) for j in range(0,11)])
axes.set_yticks([float(j/10) for j in range(0,11)])

Addition of velocities contour plot in Sage(math)

Finally, I plot it in Matplotlib

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0., 0.99, 0.01)
y = np.arange(0., 0.99, 0.01)
X, Y = np.meshgrid(x, y)
curve = (X+Y)/(1 + X*Y)
cs = plt.contour(curve, [.2,.3,.5,.7,.9,.99])
plt.clabel(cs);
plt.xlabel(r’$\frac{V}{c}\times 100$’, fontsize = 15)
plt.ylabel(r’$\frac{v}{c}\times 100$’, fontsize = 15)
plt.show()

Undoubtly, the control of the plot using Matplotlib is impressive, but somehow I do not get what the mesh does that it changes the scale of the axes $x$ and $y$.

Enjoy!

### 3 Responses

1. Just change the contour plot line to

plt.contour(X, Y, curve, [.2,.3,.5,.7,.9,.99])

to get the correct axis ranges. You can also do

X, Y = np.mgrid[0:1:100j,0:1:100j]