0

Well, Python 3 and Python 2... After sorting out some code differences, the rabbit hole just keeps on getting deeper as I try to retrofit code I don't quite understand from 3 to 2. In this case I don't see why I'm not getting the 3D plot I used to get with this code:

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import pylab as pylab
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LogNorm

f  = lambda x, y: 10 * np.cos(1 * x) * 15 * np.sin(1/2 * y) + 150
xmin, xmax, xstep = -4.5, 4.5, .2
ymin, ymax, ystep = -4.5, 4.5, .2

x, y = np.meshgrid(np.arange(xmin, xmax + xstep, xstep), np.arange(ymin, ymax + ystep, ystep))

z = f(x, y)

fig = plt.figure(figsize=(8, 5))
ax = plt.axes(projection='3d', elev=50, azim=-50)
ax.plot_surface(x, y, z, norm=LogNorm(), rstride=1, cstride=1, 
                edgecolor='none', alpha=.8, cmap=plt.cm.jet)

enter image description here

Evidently, the right plot is on the right of the image above, as shown by plugging the same equation into Wolfram alpha:

enter image description here

Antoni Parellada
  • 4,253
  • 6
  • 49
  • 114

1 Answers1

1

It's actually due to the division change described here. There are two ways to make python 2 produce the 3D plot on the right:

  1. Put from __future__ import division in front of your code;
  2. Use 0.5 rather than 1/2 in the line f = lambda x, y: 10 * np.cos(1 * x) * 15 * np.sin(1/2 * y) + 150

On the other side, to make python 3 produce the "flat" plot on the left, use 0 instead of 1/2 in the line f = lambda x, y: 10 * np.cos(1 * x) * 15 * np.sin(1/2 * y) + 150.

Though I'm not sure whether it covers everything or not, the document actually described a lot of details and might be worth checking.

Y. Luo
  • 5,622
  • 1
  • 18
  • 25