def plot(self):
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(self.meshgrid[0], self.meshgrid[1],
self.mu.reshape(self.meshgrid[0].shape), alpha=0.5, color='g')
ax.plot_wireframe(self.meshgrid[0], self.meshgrid[1],
self.environment.sample(self.meshgrid), alpha=0.5, color='b')
ax.scatter([x[0] for x in self.X], [x[1] for x in self.X], self.T, c='r',
marker='o', alpha=1.0)
plt.savefig('fig_%02d.png' % len(self.X))
python类Axes3D()的实例源码
def plot_trajectory_3D(traj):
"""
Plot airplane trajectory in 3D.
Parameters
----------
traj: object (AirplaneTrajectory instance).
AirplaneTrajectory instance.
Returns
-------
-.
"""
fig = plt.figure()
fp = Axes3D(fig)
fp.plot(traj.flight_x, traj.flight_y, traj.flight_z, label='Airplane trajectory')
fp.legend()
fp.set_xlabel('x position')
fp.set_ylabel('y position')
fp.set_zlabel('z position')
figv = plt.figure()
fv = figv.gca(projection='3d')
fv.plot(traj.flight_vx, traj.flight_vy, traj.flight_vz, label='Airplane velocity')
fv.set_xscale('linear')
fv.set_yscale('linear')
fv.set_zscale('linear')
fv.legend()
fv.set_xlabel('x velocity')
fv.set_ylabel('y velocity')
fv.set_zlabel('z velocity')
plt.show()
def PCA_n_plot():
all_feas = get_all_feas();
print 'Start PCA ...'
pca = PCA(n_components = 3,whiten = False)
new_feas = pca.fit_transform(np.array(all_feas))
Fig = plt.figure()
ax = Axes3D(Fig)
print 'Start Ploting'
ax.scatter(new_feas[:,0],new_feas[:,1],new_feas[:,2])
plt.show()
def plotSequenceForRotatingState3D(degPerStep, Sigma, stationaryDim=0, T=1000):
A = makeA_3DRotationMatrix(degPerStep, stationaryDim)
Sigma = Sigma * np.eye(3)
assert Sigma.shape == (3, 3)
X = np.zeros((T, 3))
X[0, :] = [1, 1, 1]
for t in xrange(1, T):
X[t] = np.random.multivariate_normal(np.dot(A, X[t - 1]), Sigma)
ax = Axes3D(pylab.figure())
pylab.plot(X[:, 0], X[:, 1], X[:, 2], '.')
pylab.axis('equal')
def showEachSetOfStatesIn3D():
''' Make a 3D plot in separate figure for each of the 3 states in a "set"
These three states just vary the speed of rotation and scale of noise,
from slow and large to fast and smaller.
'''
from matplotlib import pylab
from mpl_toolkits.mplot3d import Axes3D
L = len(degPerSteps)
for ii in xrange(L):
plotSequenceForRotatingState3D(-1 * degPerSteps[ii], sigma2s[ii], 2)
def _plot_sensors(pos, colors, ch_names, title, show_names, show):
"""Helper function for plotting sensors."""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from .topomap import _check_outlines, _draw_outlines
fig = plt.figure()
if pos.shape[1] == 3:
ax = Axes3D(fig)
ax = fig.gca(projection='3d')
ax.text(0, 0, 0, '', zorder=1)
ax.scatter(pos[:, 0], pos[:, 1], pos[:, 2], picker=True, c=colors)
ax.azim = 90
ax.elev = 0
else:
ax = fig.add_subplot(111)
ax.text(0, 0, '', zorder=1)
ax.set_xticks([])
ax.set_yticks([])
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None,
hspace=None)
pos, outlines = _check_outlines(pos, 'head')
_draw_outlines(ax, outlines)
ax.scatter(pos[:, 0], pos[:, 1], picker=True, c=colors)
if show_names:
for idx in range(len(pos)):
this_pos = pos[idx]
if pos.shape[1] == 3:
ax.text(this_pos[0], this_pos[1], this_pos[2], ch_names[idx])
else:
ax.text(this_pos[0], this_pos[1], ch_names[idx])
else:
picker = partial(_onpick_sensor, fig=fig, ax=ax, pos=pos,
ch_names=ch_names)
fig.canvas.mpl_connect('pick_event', picker)
fig.suptitle(title)
plt_show(show)
return fig
def fig_ax3d(**kwds):
fig = plt.figure(**kwds)
try:
ax = fig.add_subplot(111, projection='3d')
except:
# mpl < 1.0.0
ax = Axes3D(fig)
return fig, ax
def plot_figs(fig_num, elev, azim):
fig = plt.figure(fig_num, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elev, azim=azim)
ax.scatter(a[::10], b[::10], c[::10], c=density[::10], marker='+', alpha=.4)
Y = np.c_[a, b, c]
# Using SciPy's SVD, this would be:
# _, pca_score, V = scipy.linalg.svd(Y, full_matrices=False)
pca = PCA(n_components=3)
pca.fit(Y)
pca_score = pca.explained_variance_ratio_
V = pca.components_
x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min()
x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T
x_pca_plane = np.r_[x_pca_axis[:2], - x_pca_axis[1::-1]]
y_pca_plane = np.r_[y_pca_axis[:2], - y_pca_axis[1::-1]]
z_pca_plane = np.r_[z_pca_axis[:2], - z_pca_axis[1::-1]]
x_pca_plane.shape = (2, 2)
y_pca_plane.shape = (2, 2)
z_pca_plane.shape = (2, 2)
ax.plot_surface(x_pca_plane, y_pca_plane, z_pca_plane)
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
def scatters_in_3d(samples, is_labelled = False):
# PCA ???2??????
pca = PCA(n_components=3)
reduced_data = pca.fit_transform(samples)
fig = plt.figure()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=9, azim=-170)
for c, rng in [('r', (0, 80)), ('b', (80, 120))]:
xs = reduced_data[rng[0]:rng[1], 0]
ys = reduced_data[rng[0]:rng[1], 1]
zs = reduced_data[rng[0]:rng[1], 2]
ax.scatter(xs, ys, zs, c=c)
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
if is_labelled:
for ix in np.arange(len(samples)):
ax.text(reduced_data[ix, 0], reduced_data[ix, 1],reduced_data[ix, 2],
str(ix+1), verticalalignment='center', fontsize=10)
plt.show()
# ????????kNN?????
def hist2d(self, title, newfig = True):
if newfig :
fig1 = pylab.figure()
ax = Axes3D(fig1)
else:
ax = Axes3D(newfig)
dx, dy = np.indices(self.shape)
ax.plot_wireframe(dx, dy, self.image, alpha = 0.2)
pylab.title(title)
return ax
def kcv_errors(errors, range_x, range_y, label_x, label_y):
r"""Plot a 3D error surface.
Parameters
----------
errors : (N, D) ndarray
Error matrix.
range_x : array_like of N values
First axis values.
range_y : array_like of D values
Second axis values.
label_x : str
First axis label.
label_y : str
Second axis label.
Examples
--------
>>> errors = numpy.empty((20, 10))
>>> x = numpy.arange(20)
>>> y = numpy.arange(10)
>>> for i in range(20):
... for j in range(10):
... errors[i, j] = (x[i] * y[j])
...
>>> kcv_errors(errors, x, y, 'x', 'y')
>>> plt.show()
"""
fig = plt.figure()
ax = Axes3D(fig)
x_vals, y_vals = np.meshgrid(range_x, range_y)
x_idxs, y_idxs = np.meshgrid(np.arange(len(range_x)),
np.arange(len(range_y)))
ax.set_xlabel(label_x)
ax.set_ylabel(label_y)
ax.set_zlabel('$error$')
ax.plot_surface(x_vals, y_vals, errors[x_idxs, y_idxs],
rstride=1, cstride=1, cmap=cm.jet)
def state_histogram(rho, ax=None, title="", threshold=0.001):
"""
Visualize a density matrix as a 3d bar plot with complex phase encoded
as the bar color.
This code is a modified version of
`an equivalent function in qutip <http://qutip.org/docs/3.1.0/apidoc/functions.html#qutip.visualization.matrix_histogram_complex>`_
which is released under the (New) BSD license.
:param qutip.Qobj rho: The density matrix.
:param Axes3D ax: The axes object.
:param str title: The axes title.
:param float threshold: (Optional) minimum magnitude of matrix elements. Values below this
are hidden.
:return: The axis
:rtype: mpl_toolkits.mplot3d.Axes3D
"""
rho_amps = rho.data.toarray().ravel()
nqc = int(round(np.log2(rho.shape[0])))
if ax is None:
fig = plt.figure(figsize=(10, 6))
ax = Axes3D(fig, azim=-35, elev=35)
cmap = rigetti_4_color_cm
norm = mpl.colors.Normalize(-np.pi, np.pi)
colors = cmap(norm(np.angle(rho_amps)))
dzs = abs(rho_amps)
colors[:, 3] = 1.0 * (dzs > threshold)
xs, ys = np.meshgrid(range(2 ** nqc), range(2 ** nqc))
xs = xs.ravel()
ys = ys.ravel()
zs = np.zeros_like(xs)
dxs = dys = np.ones_like(xs) * 0.8
_ = ax.bar3d(xs, ys, zs, dxs, dys, dzs, color=colors)
ax.set_xticks(np.arange(2 ** nqc) + .4)
ax.set_xticklabels(basis_labels(nqc))
ax.set_yticks(np.arange(2 ** nqc) + .4)
ax.set_yticklabels(basis_labels(nqc))
ax.set_zlim3d([0, 1])
cax, kw = mpl.colorbar.make_axes(ax, shrink=.75, pad=.1)
cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)
cb.set_ticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi])
cb.set_ticklabels((r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'))
cb.set_label('arg')
ax.view_init(azim=-55, elev=45)
ax.set_title(title)
return ax
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 plot(self, plot_file=None, save_fig=False):
"""
Method to plot a file. If `plot_file` is not given it plots `self.shape`.
:param string plot_file: the filename you want to plot.
:param bool save_fig: a flag to save the figure in png or not. If True the
plot is not shown.
:return: figure: matlplotlib structure for the figure of the chosen geometry
:rtype: matplotlib.pyplot.figure
"""
if plot_file is None:
shape = self.shape
plot_file = self.infile
else:
shape = self.load_shape_from_file(plot_file)
stl_writer = StlAPI_Writer()
# Do not switch SetASCIIMode() from False to True.
stl_writer.SetASCIIMode(False)
stl_writer.Write(shape, 'aux_figure.stl')
# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
# Load the STL files and add the vectors to the plot
stl_mesh = mesh.Mesh.from_file('aux_figure.stl')
os.remove('aux_figure.stl')
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(stl_mesh.vectors / 1000))
# Get the limits of the axis and center the geometry
max_dim = np.array([\
np.max(stl_mesh.vectors[:, :, 0]) / 1000,\
np.max(stl_mesh.vectors[:, :, 1]) / 1000,\
np.max(stl_mesh.vectors[:, :, 2]) / 1000])
min_dim = np.array([\
np.min(stl_mesh.vectors[:, :, 0]) / 1000,\
np.min(stl_mesh.vectors[:, :, 1]) / 1000,\
np.min(stl_mesh.vectors[:, :, 2]) / 1000])
max_lenght = np.max(max_dim - min_dim)
axes.set_xlim(\
-.6 * max_lenght + (max_dim[0] + min_dim[0]) / 2,\
.6 * max_lenght + (max_dim[0] + min_dim[0]) / 2)
axes.set_ylim(\
-.6 * max_lenght + (max_dim[1] + min_dim[1]) / 2,\
.6 * max_lenght + (max_dim[1] + min_dim[1]) / 2)
axes.set_zlim(\
-.6 * max_lenght + (max_dim[2] + min_dim[2]) / 2,\
.6 * max_lenght + (max_dim[2] + min_dim[2]) / 2)
# Show the plot to the screen
if not save_fig:
pyplot.show()
else:
figure.savefig(plot_file.split('.')[0] + '.png')
return figure
def visualize(N_frame):
with tf.Graph().as_default():
# init the sample reader
data_generator = AudioSampleReader(data_dir)
# build the graph as the training script
in_data = tf.placeholder(
tf.float32, shape=[batch_size, FRAMES_PER_SAMPLE, NEFF])
VAD_data = tf.placeholder(
tf.float32, shape=[batch_size, FRAMES_PER_SAMPLE, NEFF])
Y_data = tf.placeholder(
tf.float32, shape=[batch_size, FRAMES_PER_SAMPLE, NEFF, 2])
# init
BiModel = Model(n_hidden, batch_size, False)
# infer embedding
embedding = BiModel.inference(in_data)
saver = tf.train.Saver(tf.all_variables())
sess = tf.Session()
# restore a model
saver.restore(sess, 'train/model.ckpt-68000')
for step in range(N_frame):
data_batch = data_generator.gen_next()
if data_batch is None:
break
# concatenate the elements in sample dict to generate batch data
in_data_np = np.concatenate(
[np.reshape(item['Sample'], [1, FRAMES_PER_SAMPLE, NEFF])
for item in data_batch])
VAD_data_np = np.concatenate(
[np.reshape(item['VAD'], [1, FRAMES_PER_SAMPLE, NEFF])
for item in data_batch])
embedding_np, = sess.run(
[embedding],
feed_dict={in_data: in_data_np,
VAD_data: VAD_data_np
})
# only plot those embeddings whose VADs are active
embedding_ac = [embedding_np[i, j, :]
for i, j in itertools.product(
range(FRAMES_PER_SAMPLE), range(NEFF))
if VAD_data_np[0, i, j] == 1]
# ipdb.set_trace()
kmean = KMeans(n_clusters=2, random_state=0).fit(embedding_ac)
# visualization using 3 PCA
pca_Data = PCA(n_components=3).fit_transform(embedding_ac)
fig = plt.figure(1, figsize=(8, 6))
ax = Axes3D(fig, elev=-150, azim=110)
# ax.scatter(pca_Data[:, 0], pca_Data[:, 1], pca_Data[:, 2],
# c=kmean.labels_, cmap=plt.cm.Paired)
ax.scatter(pca_Data[:, 0], pca_Data[:, 1], pca_Data[:, 2],
cmap=plt.cm.Paired)
ax.set_title('Embedding visualization using the first 3 PCs')
ax.set_xlabel('1st pc')
ax.set_ylabel('2nd pc')
ax.set_zlabel('3rd pc')
plt.savefig('vis/' + str(step) + 'pca.jpg')
def plotlines3d(ax3d, x,y,z, *args, **kwargs):
"""Plot x-z curves stacked along y.
Parameters
----------
ax3d : Axes3D instance
x : nd array
1d (x-axis) or 2d (x-axes are the columns)
y : 1d array
z : nd array with "y"-values
1d : the same curve will be plotted len(y) times against x (1d) or
x[:,i] (2d)
2d : each column z[:,i] will be plotted against x (1d) or each x[:,i]
(2d)
*args, **kwargs : additional args and keywords args passed to ax3d.plot()
Returns
-------
ax3d
Examples
--------
>>> x = linspace(0,5,100)
>>> y = arange(1.0,5) # len(y) = 4
>>> z = np.repeat(sin(x)[:,None], 4, axis=1)/y # make 2d
>>> fig,ax = fig_ax3d()
>>> plotlines3d(ax, x, y, z)
>>> show()
"""
assert y.ndim == 1
if z.ndim == 1:
zz = np.repeat(z[:,None], len(y), axis=1)
else:
zz = z
if x.ndim == 1:
xx = np.repeat(x[:,None], zz.shape[1], axis=1)
else:
xx = x
assert xx.shape == zz.shape
assert len(y) == xx.shape[1] == zz.shape[1]
for j in range(xx.shape[1]):
ax3d.plot(xx[:,j], np.ones(xx.shape[0])*y[j], z[:,j], *args, **kwargs)
return ax3d
def main():
cal_housing = fetch_california_housing()
# split 80/20 train-test
X_train, X_test, y_train, y_test = train_test_split(cal_housing.data,
cal_housing.target,
test_size=0.2,
random_state=1)
names = cal_housing.feature_names
print("Training GBRT...", flush=True, end='')
clf = GradientBoostingRegressor(n_estimators=100, max_depth=4,
learning_rate=0.1, loss='huber',
random_state=1)
clf.fit(X_train, y_train)
print(" done.")
print('Convenience plot with ``partial_dependence_plots``')
features = [0, 5, 1, 2, (5, 1)]
fig, axs = plot_partial_dependence(clf, X_train, features,
feature_names=names,
n_jobs=3, grid_resolution=50)
fig.suptitle('Partial dependence of house value on nonlocation features\n'
'for the California housing dataset')
plt.subplots_adjust(top=0.9) # tight_layout causes overlap with suptitle
print('Custom 3d plot via ``partial_dependence``')
fig = plt.figure()
target_feature = (1, 5)
pdp, axes = partial_dependence(clf, target_feature,
X=X_train, grid_resolution=50)
XX, YY = np.meshgrid(axes[0], axes[1])
Z = pdp[0].reshape(list(map(np.size, axes))).T
ax = Axes3D(fig)
surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=plt.cm.BuPu)
ax.set_xlabel(names[target_feature[0]])
ax.set_ylabel(names[target_feature[1]])
ax.set_zlabel('Partial dependence')
# pretty init view
ax.view_init(elev=22, azim=122)
plt.colorbar(surf)
plt.suptitle('Partial dependence of house value on median age and '
'average occupancy')
plt.subplots_adjust(top=0.9)
plt.show()
# Needed on Windows because plot_partial_dependence uses multiprocessing