In [1]:
np


Out[1]:
<module 'numpy' from '/usr/local/lib/python3.4/site-packages/numpy/__init__.py'>

In [2]:
a = np.array([0, 1, 2, 3])

In [3]:
a


Out[3]:
array([0, 1, 2, 3])

In [5]:
L = range(1000)

In [8]:
%timeit [i**2 for i in L]


1000 loops, best of 3: 617 µs per loop

In [10]:
a = np.arange(1000)

In [11]:
%timeit a**2


100000 loops, best of 3: 2.64 µs per loop

In [12]:
b = np.array([[0, 1, 2], [3, 4, 5]])

In [13]:
b


Out[13]:
array([[0, 1, 2],
       [3, 4, 5]])

In [14]:
b = np.random.randn(4)

In [15]:
b


Out[15]:
array([-0.45322863,  0.5407925 ,  0.85151674, -0.14169311])

In [16]:
np.empty?

In [17]:
x = np.linspace(0, 3, 20)

In [18]:
y = np.linspace(0, 9, 20)

In [1]:
plt.plot(x, y)       # line plot
plt.plot(x, y, 'o')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-b4253c0ddf41> in <module>()
----> 1 plt.plot(x, y)       # line plot
      2 plt.plot(x, y, 'o')

NameError: name 'x' is not defined

In [20]:
plt.plot(x, y, 'o')


Out[20]:
[<matplotlib.lines.Line2D at 0x7fa81ddcf630>]

In [22]:
%load "/home/mn/Downloads/lines3d_demo.py"

In [29]:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve label')
ax.legend()

plt.show()



In [30]:
%load "/home/mn/Downloads/wire3d_demo.py"

In [34]:
from mpl_toolkits.mplot3d import axes3d
import matplotlib
import matplotlib.pyplot as plt
import pylab
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()



In [37]:
%load "/home/mn/Downloads/surface3d_demo2.py"

In [5]:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
figsize(10,10)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
print(x)
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')

plt.show()


[[  0.00000000e+00   3.17279335e-01   6.34239197e-01 ...,   6.34239197e-01
    3.17279335e-01   1.22464680e-15]
 [  0.00000000e+00   3.16640549e-01   6.32962268e-01 ...,   6.32962268e-01
    3.16640549e-01   1.22218119e-15]
 [  0.00000000e+00   3.14726763e-01   6.29136624e-01 ...,   6.29136624e-01
    3.14726763e-01   1.21479429e-15]
 ..., 
 [  0.00000000e+00   3.14726763e-01   6.29136624e-01 ...,   6.29136624e-01
    3.14726763e-01   1.21479429e-15]
 [  0.00000000e+00   3.16640549e-01   6.32962268e-01 ...,   6.32962268e-01
    3.16640549e-01   1.22218119e-15]
 [  0.00000000e+00   3.17279335e-01   6.34239197e-01 ...,   6.34239197e-01
    3.17279335e-01   1.22464680e-15]]

In [6]:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
xlen = len(X)
Y = np.arange(-5, 5, 0.25)
ylen = len(Y)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
    for x in range(xlen):
        colors[x, y] = colortuple[(x + y) % len(colortuple)]

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
        linewidth=0, antialiased=True)

ax.set_zlim3d(-1, 1)
ax.w_zaxis.set_major_locator(LinearLocator(6))

plt.show()



In [7]:
np.outer?

In [51]:
np.arange(6) + np.arange(0, 51, 10)[:, np.newaxis]


Out[51]:
array([[ 0,  1,  2,  3,  4,  5],
       [10, 11, 12, 13, 14, 15],
       [20, 21, 22, 23, 24, 25],
       [30, 31, 32, 33, 34, 35],
       [40, 41, 42, 43, 44, 45],
       [50, 51, 52, 53, 54, 55]])

In [57]:
b = arange(24).reshape(2,3,4)

In [54]:
b


Out[54]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

In [55]:
b.shape


Out[55]:
(2, 3, 4)

In [3]:
a = arange(15).reshape(3, 5)

In [4]:
a


Out[4]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [5]:
type(a)


Out[5]:
numpy.ndarray

In [6]:
empty((2,3))


Out[6]:
array([[ 0.06824331,  0.07183185, -0.03412165],
       [ 0.05516321, -0.9591853 , -1.00962364]])

In [7]:
a.cumsum(axis=1)


Out[7]:
array([[ 0,  1,  3,  6, 10],
       [ 5, 11, 18, 26, 35],
       [10, 21, 33, 46, 60]])

In [9]:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.tri as mtri

R = 1.
r = 0.8
n = 50
m = 50

def torus_triangles(n, m):
    """ Returns triangles to mesh a (n, m) torus """
    tri = []
    for i in range(n):
        for j in range(m):
            a = i + j*(n)
            b = ((i+1) % n) + j*n
            d = i + ((j+1) % m) * n
            c = ((i+1) % n) + ((j+1) % m) * n
            tri += [[a, b, d], [b, c, d]]
    return np.array(tri, dtype=np.int32)

theta0 = np.linspace(0, (2*np.pi), n, endpoint=False)
phi0 = np.linspace(0, (2*np.pi), m, endpoint=False)
theta, phi = np.meshgrid(theta0, phi0)

x = (R + r * np.sin(phi)) * np.cos(theta)
y = (R + r * np.sin(phi)) * np.sin(theta)
z = r * np.cos(phi)

triangles = torus_triangles(n , m)
triang = mtri.Triangulation(x.ravel(), y.ravel(), triangles)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(triang, z.ravel(), lw=0.2, edgecolor="black", color="grey",
                alpha=0.5)

plt.show()



In [10]:
np.meshgrid?

In [ ]:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random

def fun(x, y):
  return x**2 + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)

zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

In [18]:
#here's pythonic way to convert your 3-tuples to 3 1d arrays.
data = [(1,2,3), (10,20,30), (11, 22, 33), (110, 220, 330)]
X,Y,Z = zip(*data)
print(X, Y, Z)


(1, 10, 11, 110) (2, 20, 22, 220) (3, 30, 33, 330)

In [20]:
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import art3d
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1.0, 0.1, 2.9])
y = np.array([2.0, 1.1, 1.2])
z = np.array([0.0, 2.1, 4.6])
fig = plt.figure()
# ax = fig.gca(projection='3d')
# ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
verts = [[[-6.1,-4.1,-2.1],
[ 2.9, 1.2, 4.6],
[ 1., 2., 0. ]]]
# polyc = art3d.Poly3DCollection(verts, cmap=cm.jet, linewidth=0.2)
# colset = []
# for i in xrange(len(verts)):
# avgzsum = verts[i,0,2] + verts[i,1,2] + verts[i,2,2]
# colset.append(avgzsum / 3.0)
#
# polyc.set_facecolors(colset)
# plt.show()
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
ax = Axes3D(fig)
# ax = fig.gca(projection='3d')
# x = [0,1,1,0]
# y = [0,0,1,1]
# z = [0,1,0,1]
verts = [zip(x, y,z)]
print (verts)
poly = Poly3DCollection(verts)
poly.set_alpha(0.6)
ax.add_collection3d(Poly3DCollection(verts))
ax.set_xlim3d(0,3)
ax.set_ylim3d(1,2)
ax.set_zlim3d(0,5)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()


[<zip object at 0x7f8330ac5f48>]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-40bb0d2ad131> in <module>()
     29 verts = [zip(x, y,z)]
     30 print (verts)
---> 31 poly = Poly3DCollection(verts)
     32 poly.set_alpha(0.6)
     33 ax.add_collection3d(Poly3DCollection(verts))

/usr/local/lib/python3.4/site-packages/matplotlib-1.4.0-py3.4-linux-x86_64.egg/mpl_toolkits/mplot3d/art3d.py in __init__(self, verts, *args, **kwargs)
    472         self.set_zsort(kwargs.pop('zsort', True))
    473 
--> 474         PolyCollection.__init__(self, verts, *args, **kwargs)
    475 
    476     _zsort_functions = {

/usr/local/lib/python3.4/site-packages/matplotlib-1.4.0-py3.4-linux-x86_64.egg/matplotlib/collections.py in __init__(self, verts, sizes, closed, **kwargs)
    799         Collection.__init__(self, **kwargs)
    800         self.set_sizes(sizes)
--> 801         self.set_verts(verts, closed)
    802 
    803     def set_verts(self, verts, closed=True):

/usr/local/lib/python3.4/site-packages/matplotlib-1.4.0-py3.4-linux-x86_64.egg/mpl_toolkits/mplot3d/art3d.py in set_verts(self, verts, closed)
    526     def set_verts(self, verts, closed=True):
    527         '''Set 3D vertices.'''
--> 528         self.get_vector(verts)
    529         # 2D verts will be updated at draw time
    530         PolyCollection.set_verts(self, [], closed)

/usr/local/lib/python3.4/site-packages/matplotlib-1.4.0-py3.4-linux-x86_64.egg/mpl_toolkits/mplot3d/art3d.py in get_vector(self, segments3d)
    510         for p in segments3d:
    511             points.extend(p)
--> 512             ei = si+len(p)
    513             segis.append((si, ei))
    514             si = ei

TypeError: object of type 'zip' has no len()

In [ ]:
import mpl_toolkits.mplot3d as a3
import matplotlib.colors as colors
import pylab as pl
import scipy as sp

ax = a3.Axes3D(pl.figure())
for i in range(10000):
    vtx = sp.rand(3,3)
    tri = a3.art3d.Poly3DCollection([vtx])
    tri.set_color(colors.rgb2hex(sp.rand(3)))
    tri.set_edgecolor('k')
    ax.add_collection3d(tri)
pl.show()

In [1]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.tri as mtri

figsize(10,10)

# u, v are parameterisation variables
u = (np.linspace(0, 2.0 * np.pi, endpoint=True, num=50) * np.ones((10, 1)))
assert u.shape == (10, 50)
u = u.flatten()
v = np.repeat(np.linspace(-0.5, 0.5, endpoint=True, num=10), repeats=50)#.flatten()
assert v.shape == (500,)

# This is the Mobius mapping, taking a u, v pair and returning an x, y, z
# triple
x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u)
y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u)
z = 0.5 * v * np.sin(u / 2.0)

# Triangulate parameter space to determine the triangles
import matplotlib.tri as mtri
tri = mtri.Triangulation(u, v)
print(tri.triangles)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

# The triangles in parameter space determine which x, y, z points are
# connected by an edge
ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap=plt.cm.Spectral)

ax.set_zlim(-1, 1)

# First create the x and y coordinates of the points.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)

angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[...,np.newaxis], n_radii, axis=1)
angles[:,1::2] += np.pi/n_angles

x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
z = (np.cos(radii)*np.cos(angles*3.0)).flatten()

# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = mtri.Triangulation(x, y)

# Mask off unwanted triangles.
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
triang.set_mask(mask)

# tripcolor plot.
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.plot_trisurf(triang, z, cmap=plt.cm.CMRmap)
plt.show()


[[226 277 276]
 [227 277 226]
 [226 275 225]
 ..., 
 [339 388 338]
 [338 288 339]
 [288 289 339]]