def draw2dsurface(X, Y, zf):
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(X, Y)
Z = X*0
for i in range(len(X)):
for j in range(len(X[0])):
Z[i][j] = zf([X[i][j], Y[i][j]])
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(np.min(Z.flatten()), np.max(Z.flatten()))
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
# plt.show()
python类LinearLocator()的实例源码
def paint_surf(a, b, c, points=None):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.arange(-1, 1, 0.05)
Y = np.arange(-1, 1, 0.05)
X, Y = np.meshgrid(X, Y)
Z = -(X*a + Y*b + c)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
if points != None:
x1 = points[:, 0]
y1 = points[:, 1]
z1 = points[:, 2]
ax.scatter(x1, y1, z1, c='r')
pl.show()
def paint_surfs(surfs, points, xlim=(-1.0, 1.0), ylim=(-1.0, 1.0), zlim=(-1.1, 1.1)):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
for ans, surf_id in zip(surfs, range(len(surfs))):
a, b, c = ans[0][0], ans[0][1], ans[0][2]
X = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/100.0)
Y = np.arange(ylim[0], ylim[1], (ylim[1]-ylim[0])/100.0)
X, Y = np.meshgrid(X, Y)
Z = -(X*a + Y*b + c)
# ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
# fig.colorbar(s, shrink=0.5, aspect=5)
s = ax.plot_wireframe(X, Y, Z, rstride=15, cstride=15)
x1 = ans[2][:, 0]
y1 = ans[2][:, 1]
z1 = ans[2][:, 2]
ax.scatter(x1, y1, z1, c='crkgmy'[surf_id])
ax.set_zlim(zlim[0], zlim[1])
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# x1 = points[:, 0]
# y1 = points[:, 1]
# z1 = points[:, 2]
# ax.scatter(x1, y1, z1, c='r')
pl.show()
def paint_surfs(surfs, points, xlim=(-1.0, 1.0), ylim=(-1.0, 1.0), zlim=(-1.1, 1.1), show = True):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
for ans, surf_id in zip(surfs, range(len(surfs))):
a, b, c = ans[0][0], ans[0][1], ans[0][2]
X = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/100.0)
Y = np.arange(ylim[0], ylim[1], (ylim[1]-ylim[0])/100.0)
X, Y = np.meshgrid(X, Y)
Z = -(X*a + Y*b + c)
s = ax.plot_wireframe(X, Y, Z, rstride=15, cstride=15)
x1 = ans[2][:, 0]
y1 = ans[2][:, 1]
z1 = ans[2][:, 2]
# tan_color = np.ones((len(x1), len(y1))) * np.arctan2(len(surfs)) # c='crkgmycrkgmycrkgmycrkgmy'[surf_id]
# ax.scatter(x1, y1, z1, c='rcykgm'[surf_id % 6], marker='o^sd*+xp'[int(surf_id/6)])
ax.set_zlim(zlim[0], zlim[1])
# ax.set_ylim(ylim[0], ylim[1])
# ax.set_xlim(xlim[0], xlim[1])
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
if show:
pl.show()
def plot_3d(model, phi, x_min, x_max, y_min, y_max, z_min, z_max, filename=None):
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(x_min, x_max, 5)
Y = np.arange(y_min, y_max, 5)
X, Y = np.meshgrid(X, Y)
x, y = np.reshape(X, len(X)**2), np.reshape(Y, len(Y)**2)
Z = model(np.matrix(phi(np.array([x, y], dtype=np.float32).T)))
Z = np.reshape(Z, [len(X), len(X)])
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False, shade=True)
# Customize the z axis.
ax.set_zlim(z_min, z_max)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
code(by cf).py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def plot_surface(self):
fig = plt.figure(figsize = (8,8))
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1)), np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1)))
surf = ax.plot_surface(X, Y, self.lattice_in, rstride=1, cstride=1,cmap = cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=10)
def clear(self):
self.graph.cla()
zero = dt.datetime.fromtimestamp(0)
one = dt.datetime.fromtimestamp(1)
x, y = [zero, one], [-1, -1]
self.graph.set_xlim(zero, one)
self.graph.set_ylim(0, 1)
self.power_line, = self.graph.plot(x, y, color='red')
self.graph.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d %H:%M:%S"))
self.graph.xaxis.set_major_locator(LinearLocator(numticks=6))
plt.setp(self.graph.get_xticklabels(), rotation=10)
self.graph.set_ylabel("Power (kW)")
def paint_points(points, show = True, title = '', xlim = None, ylim = None, zlim = None):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
if xlim == None:
xlim = (np.min(points[:, 0]), np.max(points[:, 0]))
if ylim == None:
ylim = (np.min(points[:, 1]), np.max(points[:, 1]))
if zlim == None:
zlim = (np.min(points[:, 2]), np.max(points[:, 2]))
x1 = points[:, 0]
y1 = points[:, 1]
z1 = points[:, 2]
ax.scatter(x1, y1, z1, c='r')
ax.set_zlim(zlim[0], zlim[1])
ax.set_ylim(ylim[0], ylim[1])
ax.set_xlim(xlim[0], xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
def paint_surfs(surfs, points, show = True, title = ''):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
xlim = (np.min(points[:, 0]), np.max(points[:, 0]))
ylim = (np.min(points[:, 1]), np.max(points[:, 1]))
zlim = (np.min(points[:, 2]), np.max(points[:, 2]))
for ans, surf_id in zip(surfs, range(len(surfs))):
a, b, c = ans.args[0], ans.args[1], ans.args[2]
X = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/100.0)
Y = np.arange(ylim[0], ylim[1], (ylim[1]-ylim[0])/100.0)
X, Y = np.meshgrid(X, Y)
Z = -(X*a + Y*b + c)
s = ax.plot_wireframe(X, Y, Z, rstride=15, cstride=15)
x1 = ans.points[:, 0]
y1 = ans.points[:, 1]
z1 = ans.points[:, 2]
ax.scatter(x1, y1, z1, c='rcykgm'[surf_id % 6], marker='o^sd*+xp'[int(surf_id/6)])
ax.set_zlim(zlim[0], zlim[1])
# ax.set_ylim(ylim[0], ylim[1])
# ax.set_xlim(xlim[0], xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
def paint_surfs(surfs, points, show = True, title = ''):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
xlim = (np.min(points[:, 0]), np.max(points[:, 0]))
ylim = (np.min(points[:, 1]), np.max(points[:, 1]))
zlim = (np.min(points[:, 2]), np.max(points[:, 2]))
for ans, surf_id in zip(surfs, range(len(surfs))):
a, b, c = ans.args[0], ans.args[1], ans.args[2]
X = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/100.0)
Y = np.arange(ylim[0], ylim[1], (ylim[1]-ylim[0])/100.0)
X, Y = np.meshgrid(X, Y)
Z = -(X*a + Y*b + c)
s = ax.plot_wireframe(X, Y, Z, rstride=15, cstride=15)
x1 = ans.points[:, 0]
y1 = ans.points[:, 1]
z1 = ans.points[:, 2]
ax.scatter(x1, y1, z1, c='rcykgm'[surf_id % 6], marker='o^sd*+xp'[int(surf_id/6)])
ax.set_zlim(zlim[0], zlim[1])
ax.set_ylim(ylim[0], ylim[1])
ax.set_xlim(xlim[0], xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
def paint_points(points, show = True, title = '', xlim = None, ylim = None, zlim = None):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
if xlim == None:
xlim = (np.min(points[:, 0]), np.max(points[:, 0]))
if ylim == None:
ylim = (np.min(points[:, 1]), np.max(points[:, 1]))
if zlim == None:
zlim = (np.min(points[:, 2]), np.max(points[:, 2]))
x1 = points[:, 0]
y1 = points[:, 1]
z1 = points[:, 2]
ax.scatter(x1, y1, z1, c='r')
ax.set_zlim(zlim[0], zlim[1])
ax.set_ylim(ylim[0], ylim[1])
ax.set_xlim(xlim[0], xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
homework_13_3.py 文件源码
项目:computationalphysics_N2014301020131
作者: Nucleus2014
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def plot_3d(self,ax,x1,x2,y1,y2): # give 3d plot the potential
self.x=linspace(x1,x2,self.n)
self.y=linspace(y2,y1,self.n)
self.x,self.y=meshgrid(self.x,self.y)
self.surf=ax.plot_surface(self.x,self.y,self.V, rstride=1, cstride=1, cmap=cm.coolwarm)
ax.set_xlim(x1,x2)
ax.set_ylim(y1,y2)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f'))
ax.set_xlabel('x (m)',fontsize=14)
ax.set_ylabel('y (m)',fontsize=14)
ax.set_zlabel('Electric potential (V)',fontsize=14)
ax.set_title('Potential near capacitor',fontsize=18)
homework_13_1.py 文件源码
项目:computationalphysics_N2014301020131
作者: Nucleus2014
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def plot_3d(self,ax,x1,x2,y1,y2): # give 3d plot the potential
self.x=linspace(x1,x2,self.n)
self.y=linspace(y2,y1,self.n)
self.x,self.y=meshgrid(self.x,self.y)
self.surf=ax.plot_surface(self.x,self.y,self.V, rstride=1, cstride=1, cmap=cm.coolwarm)
ax.set_xlim(x1,x2)
ax.set_ylim(y1,y2)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f'))
ax.set_xlabel('x (m)',fontsize=14)
ax.set_ylabel('y (m)',fontsize=14)
ax.set_zlabel('Electric potential (V)',fontsize=14)
ax.set_title('Potential near capacitor',fontsize=18)
homework_13_2.py 文件源码
项目:computationalphysics_N2014301020131
作者: Nucleus2014
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def plot_3d(self,ax,x1,x2,y1,y2): # give 3d plot the potential
self.x=linspace(x1,x2,self.n)
self.y=linspace(y2,y1,self.n)
self.x,self.y=meshgrid(self.x,self.y)
self.surf=ax.plot_surface(self.x,self.y,self.V, rstride=1, cstride=1, cmap=cm.coolwarm)
ax.set_xlim(x1,x2)
ax.set_ylim(y1,y2)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f'))
ax.set_xlabel('x (m)',fontsize=14)
ax.set_ylabel('y (m)',fontsize=14)
ax.set_zlabel('Electric potential (V)',fontsize=14)
ax.set_title('Potential near capacitor',fontsize=18)
def plot_3d(objective_function, length=20):
"""
Plot 3D functions
:param objective_function:
:type objective_function:
:param length:
:type length:
:return:
:rtype:
"""
bounds = objective_function.get_bounds()
if len(bounds) != 2:
return
x_grid = np.linspace(bounds[0][0], bounds[0][1], length)
y_grid = np.linspace(bounds[1][0], bounds[1][1], length)
x_grid, y_grid = np.meshgrid(x_grid, y_grid)
grid = np.vstack((x_grid.flatten(), y_grid.flatten())).T
z_points = objective_function.evaluate(grid)
z_points = z_points.reshape(length, length)
fig = pyplot.figure()
axis = fig.gca(projection='3d')
surf = axis.plot_surface(x_grid, y_grid,
z_points, rstride=1, cstride=1,
cmap=cm.cool, linewidth=0, antialiased=False,
alpha=0.3)
axis.contour(x_grid.tolist(), y_grid.tolist(), z_points.tolist(),
zdir='z', offset=z_points.min(), cmap=cm.cool)
axis.set_xlim(bounds[0][0], bounds[0][1])
axis.set_ylim(bounds[1][0], bounds[1][1])
pyplot.title(objective_function.__class__.__name__)
axis.zaxis.set_major_locator(LinearLocator(10))
axis.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
pyplot.show()
def plot(self, slice_index=None, handle=False, figure=None, ax_xy=None,
vmin=None, vmax=None, cmap=None):
import matplotlib.pyplot as plt
from matplotlib import ticker
ax_xy, ax_xz, ax_yz, ax_cb = self.get_plot_axes(figure, ax_xy)
if figure is None:
figure = ax_xy.get_figure()
if slice_index is None:
slice_index = tuple(int(v) for v in
(self.nx/2, self.ny/2, self.nz/2))
if slice_index == 'max':
slice_index = self.get_ijk_max()
if slice_index == 'min':
slice_index = self.get_ijk_min()
hnd = ax_xy.imshow(np.transpose(self.array[:, :, slice_index[2]]),
vmin=vmin, vmax=vmax, cmap=cmap,
origin='lower', extent=self.get_xy_extent(),
zorder=-10)
ax_xy.set_adjustable('box-forced')
ax_xz.imshow(np.transpose(self.array[:, slice_index[1], :]),
vmin=vmin, vmax=vmax, cmap=cmap,
origin='lower', extent=self.get_xz_extent(),
aspect='auto', zorder=-10)
ax_xz.set_adjustable('box-forced')
ax_yz.imshow(self.array[slice_index[0], :, :],
vmin=vmin, vmax=vmax, cmap=cmap,
origin='lower', extent=self.get_zy_extent(),
aspect='auto', zorder=-10)
ax_yz.set_adjustable('box-forced')
x_slice, y_slice, z_slice = self.get_xyz(*slice_index)
ax_xy.axhline(y_slice, color='w', linestyle='dashed', zorder=-1)
ax_xy.axvline(x_slice, color='w', linestyle='dashed', zorder=-1)
ax_xz.axhline(z_slice, color='w', linestyle='dashed', zorder=-1)
ax_yz.axvline(z_slice, color='w', linestyle='dashed', zorder=-1)
fmt = '%.1e' if self.max() <= 0.01 else '%.2f'
cb = figure.colorbar(hnd, cax=ax_cb, orientation='horizontal',
format=fmt)
cb.locator = ticker.LinearLocator(numticks=3)
cb.update_ticks()
if handle:
return (ax_xy, ax_xz, ax_yz), cb
else:
plt.show()
def animation3D(agents, function, lb, ub, sr=False):
side = np.linspace(lb, ub, 45)
X, Y = np.meshgrid(side, side)
zs = np.array([function([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='jet',
linewidth=0, antialiased=False)
ax.set_xlim(lb, ub)
ax.set_ylim(lb, ub)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
iter = len(agents)
n = len(agents[0])
t = np.array([np.ones(n) * i for i in range(iter)]).flatten()
b = []
[[b.append(agent) for agent in epoch] for epoch in agents]
c = [function(x) for x in b]
a = np.asarray(b)
df = pd.DataFrame({"time": t, "x": a[:, 0], "y": a[:, 1], "z": c})
def update_graph(num):
data = df[df['time'] == num]
graph._offsets3d = (data.x, data.y, data.z)
title.set_text(function.__name__ + " " * 45 + 'iteration: {}'.format(
num))
title = ax.set_title(function.__name__ + " " * 45 + 'iteration: 0')
data = df[df['time'] == 0]
graph = ax.scatter(data.x, data.y, data.z, color='black')
ani = matplotlib.animation.FuncAnimation(fig, update_graph, iter,
interval=50, blit=False)
if sr:
ani.save('result.mp4')
plt.show()
def __init__(self, parent=None, width=5, height=4, dpi=80):
self.fig = Figure(figsize=(width, height), dpi=dpi, facecolor='white')
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
# Create graphs and lines
self.graph_power = self.fig.add_subplot(211)
self.graph_error = self.fig.add_subplot(212)
zero = dt.datetime.fromtimestamp(0)
one = dt.datetime.fromtimestamp(1)
x, y = [zero, one], [0, 0]
self.predict_line, = self.graph_power.plot(x, y, color='k', linewidth=2)
self.target_line, = self.graph_power.plot(x, y, color='b', linestyle='--', linewidth=2)
self.error_line, = self.graph_error.plot(x, y, color='r')
self.color_spans = []
# Change settings of graph
self.graph_power.set_ylabel("Power (kW)")
self.graph_error.set_ylabel("Error (kW)")
self.graph_power.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d %H:%M:%S"))
self.graph_error.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d %H:%M:%S"))
self.graph_power.xaxis.set_major_locator(LinearLocator(numticks=7))
self.graph_error.xaxis.set_major_locator(LinearLocator(numticks=7))
# Add legend
self.graph_power.legend([self.target_line, self.predict_line], ['Actual Value', 'Predicted Value'])
#self.graph_error.legend([self.error_line], ['Error Value'])
# Rotate dates slightly
plt.setp(self.graph_power.get_xticklabels(), rotation=10)
plt.setp(self.graph_error.get_xticklabels(), rotation=10)
# Let graph expand with window
self.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.updateGeometry()
self.fig.tight_layout()
self.draw()
# Update the graph using the given data
# 'times' should be datetime objects
# 'target' should be float values in Watts
# 'predict' should be float values in Watts
def plot(self, slice_index=None, handle=False, figure=None, ax_xy=None,
vmin=None, vmax=None, cmap=None, array=None):
import matplotlib.pyplot as plt
from matplotlib import ticker
if array is None:
if self.array is None:
return
else:
array = self.array
ax_xy, ax_xz, ax_yz, ax_cb = self.get_plot_axes(figure, ax_xy)
if figure is None:
figure = ax_xy.get_figure()
if slice_index is None:
slice_index = list(map(int, (self.nx/2, self.ny/2, self.nz/2)))
if slice_index == 'max':
slice_index = self.get_ijk_max()
if slice_index == 'min':
slice_index = self.get_ijk_min()
if vmin is None:
vmin = np.nanmin(array)
if vmax is None:
vmax = np.nanmax(array)
hnd = ax_xy.imshow(np.transpose(array[:, :, slice_index[2]]),
vmin=vmin, vmax=vmax, cmap=cmap,
origin='lower', extent=self.get_xy_extent(),
zorder=-10)
ax_xy.set_adjustable('box-forced')
ax_xz.imshow(np.transpose(array[:, slice_index[1], :]),
vmin=vmin, vmax=vmax, cmap=cmap,
origin='lower', extent=self.get_xz_extent(),
aspect='auto', zorder=-10)
ax_xz.set_adjustable('box-forced')
ax_yz.imshow(array[slice_index[0], :, :],
vmin=vmin, vmax=vmax, cmap=cmap,
origin='lower', extent=self.get_zy_extent(),
aspect='auto', zorder=-10)
ax_yz.set_adjustable('box-forced')
x_slice, y_slice, z_slice = self.get_xyz(*slice_index)
ax_xy.axhline(y_slice, color='w', linestyle='dashed', zorder=-1)
ax_xy.axvline(x_slice, color='w', linestyle='dashed', zorder=-1)
ax_xz.axhline(z_slice, color='w', linestyle='dashed', zorder=-1)
ax_yz.axvline(z_slice, color='w', linestyle='dashed', zorder=-1)
fmt = '%.1e' if np.nanmax(array) <= 0.01 else '%.2f'
cb = figure.colorbar(
hnd, cax=ax_cb, orientation='horizontal', format=fmt)
cb.locator = ticker.LinearLocator(numticks=3)
cb.update_ticks()
if handle:
return (ax_xy, ax_xz, ax_yz), cb
else:
plt.show()