def plot_path(ax, path, color='green'): path_vertices = [] for i in range(0, len(path)): path_vertices.append(path[i].end_effector_pos) path_vertices = list(map(arr_to_int, path_vertices)) paths = [(path_vertices[i], path_vertices[i + 1]) for i in range(len(path_vertices) - 1)] if color != 'green': lc2 = art3d.Line3DCollection(paths, color=color, linewidths=3) else: lc2 = art3d.Line3DCollection(paths, colors=color, linewidths=3) ax.add_collection(lc2)
def showSTL(self): # Get the x, y, z coordinates contained in the mesh structure that are the # vertices of the triangular faces of the object x = self.mesh.x.flatten() y = self.mesh.y.flatten() z = self.mesh.z.flatten() obj_mesh = copy.deepcopy(self.mesh) obj_mesh.transform(Transforms.newRotationMatrix('z', 90 / 180 * 3.14)) # Get the vectors that define the triangular faces that form the 3D object kong_vectors = obj_mesh.vectors # Create the 3D object from the x,y,z coordinates and add the additional array of ones to # represent the object using homogeneous coordinates kong = np.array([x.T, y.T, z.T, np.ones(x.size)]) fig = plt.figure(2) axes1 = plt.axes(projection='3d') # Plot and render the faces of the object axes1.add_collection3d(art3d.Poly3DCollection(kong_vectors)) # Plot the contours of the faces of the object axes1.add_collection3d( art3d.Line3DCollection(kong_vectors, colors='k', linewidths=0.2, linestyles='-')) # Plot the vertices of the object axes1.plot(kong[0, :], kong[1, :], kong[2, :], 'k.') # Set axes and their aspect axes1.auto_scale_xyz(kong[0, :], kong[1, :], kong[2, :]) Transforms.set_axes_equal(axes1) # Show the plots plt.show()
def wire_cmap(wires, ax, cmap='hsv'): """ Add a colormap to a set of wires (returned form ax.plot_wireframe)""" # Retrive data from internal storage of plot_wireframe, then delete it if wires._segments3d.ndim != 3: raise PlotError('Wireframe colormapping for non-squre data (ie same ' 'number rows and columns) is not supported.') nx, ny, _ = np.shape(wires._segments3d) wire_x = np.array(wires._segments3d)[:, :, 0].ravel() wire_y = np.array(wires._segments3d)[:, :, 1].ravel() wire_z = np.array(wires._segments3d)[:, :, 2].ravel() wires.remove() # create data for a LineCollection wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)]) wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)]) wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)]) to_delete = np.arange(0, nx * ny, ny) wire_x1 = np.delete(wire_x1, to_delete, axis=1) wire_y1 = np.delete(wire_y1, to_delete, axis=1) wire_z1 = np.delete(wire_z1, to_delete, axis=1) scalars = np.delete(wire_z, to_delete) segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(wire_x1.T, wire_y1.T, wire_z1.T)] # Plots the wireframe by a a line3DCollection new_wires = art3d.Line3DCollection(segs, cmap=cmap) new_wires.set_array(scalars) ax.add_collection(new_wires) return new_wires
def colored_line_collection( xyz: np.ndarray, colors: ListOrArray, plot_mode: PlotMode = PlotMode.xy, linestyles: str = "solid", step: int = 1, alpha: float = 1. ) -> typing.Union[LineCollection, art3d.LineCollection]: if len(xyz) / step != len(colors): raise PlotException( "color values don't have correct length: %d vs. %d" % (len(xyz) / step, len(colors))) x_idx, y_idx, z_idx = plot_mode_to_idx(plot_mode) xs = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1:step, x_idx], xyz[1::step, x_idx])] ys = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1:step, y_idx], xyz[1::step, y_idx])] if plot_mode == PlotMode.xyz: zs = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1:step, z_idx], xyz[1::step, z_idx])] segs_3d = [list(zip(x, y, z)) for x, y, z in zip(xs, ys, zs)] line_collection = art3d.Line3DCollection(segs_3d, colors=colors, alpha=alpha, linestyles=linestyles) else: segs_2d = [list(zip(x, y)) for x, y in zip(xs, ys)] line_collection = LineCollection(segs_2d, colors=colors, alpha=alpha, linestyle=linestyles) return line_collection
def colored_line_collection(xyz, colors, plot_mode=PlotMode.xy, linestyles="solid", step=1): if len(xyz) / step != len(colors): raise PlotException( "color values don't have correct length: %d vs. %d" % (len(xyz) / step, len(colors))) x_idx, y_idx, z_idx = plot_mode_to_idx(plot_mode) xs = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1:step, x_idx], xyz[1::step, x_idx])] ys = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1:step, y_idx], xyz[1::step, y_idx])] if plot_mode == PlotMode.xyz: zs = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1:step, z_idx], xyz[1::step, z_idx])] segs = [list(zip(x, y, z)) for x, y, z in zip(xs, ys, zs)] line_collection = art3d.Line3DCollection(segs, colors=colors, linestyles=linestyles) else: segs = [list(zip(x, y)) for x, y in zip(xs, ys)] line_collection = LineCollection(segs, colors=colors, linestyle=linestyles) return line_collection
def plot_3d(G, obstacles, radius, path=None): ax = plt.axes(projection='3d') xdata = [x for x, y, z in G.vertices] ydata = [y for x, y, z in G.vertices] zdata = [z for x, y, z in G.vertices] lines = [(G.vertices[edge[0]], G.vertices[edge[1]]) for edge in G.edges] lc = art3d.Line3DCollection(lines, colors='black', linewidths=1) ax.add_collection(lc) if path is not None: paths = [(path[i], path[i + 1]) for i in range(len(path) - 1)] lc2 = art3d.Line3DCollection(paths, colors='green', linewidths=3) ax.add_collection(lc2) ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Blues'); plt.show()
def plot_arm_configs(ax, path): path_arm_edges = [] for i in range(0, len(path)): path_arm_edges.append(([0, 0, 0], path[i].joint_positions[0])) path_arm_edges.append((path[i].joint_positions[0], path[i].joint_positions[1])) lc3 = art3d.Line3DCollection(path_arm_edges, colors='green', linewidths=1) ax.add_collection(lc3)
def plot_warped_grid_3d(f, mins, maxes, xres=.1, yres=.1, zres=.04, color='gray', draw=True): xmin, ymin, zmin = mins xmax, ymax, zmax = maxes nfine = 30 xcoarse = np.arange(xmin, xmax, xres) xmax = xcoarse[-1] ycoarse = np.arange(ymin, ymax, yres) ymax = ycoarse[-1] if zres == -1: zcoarse = [(zmin + zmax) / 2.] else: zcoarse = np.arange(zmin, zmax, zres) zmax = zcoarse[-1] xfine = np.linspace(xmin, xmax, nfine) yfine = np.linspace(ymin, ymax, nfine) zfine = np.linspace(zmin, zmax, nfine) lines = [] if len(zcoarse) > 1: for x in xcoarse: for y in ycoarse: xyz = np.zeros((nfine, 3)) xyz[:, 0] = x xyz[:, 1] = y xyz[:, 2] = zfine lines.append(f(xyz)) for y in ycoarse: for z in zcoarse: xyz = np.zeros((nfine, 3)) xyz[:, 0] = xfine xyz[:, 1] = y xyz[:, 2] = z lines.append(f(xyz)) for z in zcoarse: for x in xcoarse: xyz = np.zeros((nfine, 3)) xyz[:, 0] = x xyz[:, 1] = yfine xyz[:, 2] = z lines.append(f(xyz)) lc = art3d.Line3DCollection(lines, colors=color, lw=1) ax = plt.gca() ax.add_collection(lc) if draw: plt.draw()
def convert_to_colormap_lines(cmap, pts): line_list = [] init_pt = pts[0] colors = [cmap(x) for x in np.linspace(0, 1, len(pts))] for pt in pts: line_list.append([init_pt, pt]) init_pt = pt #NEED THESE FOR COLORING lines = art3d.Line3DCollection(line_list, colors=colors) return lines
def plot_phase_surface(sess, frame, flip=False, cut_thre=2 * np.pi * 0.75): fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(111, projection='3d') _, size_h, size_w = sess.data['phase'].shape y = np.arange(size_h) x = np.arange(size_w) X, Y = np.meshgrid(x, y) Z = sess.data['phase'][frame, :, :] if flip: wire = ax.plot_wireframe(X[::-1], Y, Z) else: wire = ax.plot_wireframe(X, Y[::-1], Z) ax.set_zlim(-np.pi, np.pi) # Retrive data from internal storage of plot_wireframe, then delete it nx, ny, _ = np.shape(wire._segments3d) wire_x = np.array(wire._segments3d)[:, :, 0].ravel() wire_y = np.array(wire._segments3d)[:, :, 1].ravel() wire_z = np.array(wire._segments3d)[:, :, 2].ravel() wire.remove() # create data for a LineCollection wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)]) wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)]) wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)]) to_delete = np.arange(0, nx * ny, ny) wire_x1 = np.delete(wire_x1, to_delete, axis=1) wire_y1 = np.delete(wire_y1, to_delete, axis=1) wire_z1 = np.delete(wire_z1, to_delete, axis=1) scalars = np.delete((wire_z1[0, :] + wire_z1[1, :]) / 2., to_delete) segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(wire_x1.T, wire_y1.T, wire_z1.T)] # delete false phase discontinuity to_delete = np.where( np.array([abs(seg[0][2] - seg[1][2]) for seg in segs]) > cut_thre)[0] segs = np.delete(np.array(segs), to_delete, axis=0) segs = [seg for seg in segs] # Plots the wireframe by a a line3DCollection my_wire = art3d.Line3DCollection(segs, cmap="jet") my_wire.set_array(scalars) ax.add_collection(my_wire) plt.colorbar(my_wire)
def colored_line_collection(xyz, colors, plot_mode=PlotMode.xy, linestyles="solid"): if len(xyz) != len(colors): raise PlotException("color values must have same length as xyz data: %d vs. %d" % (len(xyz), len(colors))) x_idx, y_idx, z_idx = plot_mode_to_idx(plot_mode) xs = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1, x_idx], xyz[1:, x_idx])] ys = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1, y_idx], xyz[1:, y_idx])] if plot_mode == PlotMode.xyz: zs = [[x_1, x_2] for x_1, x_2 in zip(xyz[:-1, z_idx], xyz[1:, z_idx])] segs = [list(zip(x, y, z)) for x, y, z in zip(xs, ys, zs)] line_collection = art3d.Line3DCollection(segs, colors=colors, linestyles=linestyles) else: segs = [list(zip(x, y)) for x, y in zip(xs, ys)] line_collection = LineCollection(segs, colors=colors, linestyle=linestyles) return line_collection
def create_line(zipped_list, ax, dict_color): lst_pt = zipped_list[0] color = np.random.rand( 3, ) if (not zipped_list[1]) else dict_color[zipped_list[1]] if (len(lst_pt) == 1): list_solo_x, list_solo_y, list_solo_z = [lst_pt[0][0] ], [lst_pt[0][1] ], [lst_pt[0][2]] ax.plot(list_solo_x, list_solo_y, list_solo_z, marker='o', linestyle="none", color=color) else: ax.add_collection3d(art3d.Line3DCollection([lst_pt], color=color))
def wire_cmap(wires, ax, cmap='hsv'): """ Add a colormap to a set of wires (returned form ax.plot_wireframe)""" # Retrive data from internal storage of plot_wireframe, then delete it print wires._segments3d.shape, 'segments shape' # nx, ny, _ = np.shape(wires._segments3d) #try: #nx, ny, _ = np.shape(wires._segments3d) #except ValueError: #raise PlotError("WireCmap only supported for 2d mesh mesh.") nx = len(wires._segments3d) ny = len(wires._segments3d[0]) allx = [] for i in range(nx): allx.append(wires._segments3d[i]) wire_y = np.array([wires._segments3d[i][:, 1] for i in range(nx)]).ravel() wire_z = np.array([wires._segments3d[i][:, 2] for i in range(nx)]).ravel() # wire_x = np.array(wires._segments3d)[:, :, 0].ravel() # wire_y = np.array(wires._segments3d)[:, :, 1].ravel() # wire_z = np.array(wires._segments3d)[:, :, 2].ravel() wires.remove() # create data for a LineCollection wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)]) wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)]) wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)]) to_delete = np.arange(0, nx * ny, ny) wire_x1 = np.delete(wire_x1, to_delete, axis=1) wire_y1 = np.delete(wire_y1, to_delete, axis=1) wire_z1 = np.delete(wire_z1, to_delete, axis=1) scalars = np.delete(wire_z, to_delete) print scalars, 'scalars' print wire_x.shape segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(wire_x1.T, wire_y1.T, wire_z1.T)] # Plots the wireframe by a a line3DCollection new_wires = art3d.Line3DCollection(segs, cmap=cmap) new_wires.set_array(scalars) ax.add_collection(new_wires) return new_wires
def __init__(self, ax, edge_num): load_segs = np.array(edge_num*[[[0, 0, 0],[1, 1, 1]]]) colors = edge_num*["k"] self.edge_num = edge_num self.load = art3d.Line3DCollection( load_segs, colors=colors, linewidths=1.5 ) ax.add_collection3d(self.load) verts = [3*[[1, 1, 1]]] self.cover = art3d.Poly3DCollection(verts) self.cover.set_facecolor(colors="k") self.cover.set_edgecolor(colors="k") self.cover.set_alpha(alpha=0.3) ax.add_collection3d(self.cover)
def errorbar3d_z(xs, ys, means, stds, mean_label, std_label, color, alpha, mean_shadow=False): kwargs = { "color": color, "zorder": 10, } # Means ax.scatter(xs, ys, means, label=mean_label, marker="x", s=1, **kwargs) # Mean shadow if mean_shadow: ax.scatter(xs, ys, np.zeros(len(means)), c="black", alpha=1.0, label="shadow") # label = "shadow", # Error bar lines # points, line_segment_pairs = sigma_coordinates(xs, ys, means, stds) # points, pairs_good, pairs_bad_1, pairs_bad_2 = sigma_coordinates(xs, ys, means, stds) points, pairs_good = sigma_coordinates(xs, ys, means, stds) barline_collection = art3d.Line3DCollection(list(zip(*pairs_good)), colors=color, alpha=alpha, linewidths=0.5) ax.add_collection(barline_collection) # barline_collection = art3d.Line3DCollection(list(zip(*pairs_bad_1)), colors = "purple", alpha = alpha, linewidths = 0.5) # ax.add_collection(barline_collection) # barline_collection = art3d.Line3DCollection(list(zip(*pairs_bad_2)), colors = "blue", alpha = alpha, linewidths = 0.5) # ax.add_collection(barline_collection) ax.scatter(*points, marker="_", label=std_label, c=color, alpha=alpha)
def colorline3(x, y, z, cm=plt.get_cmap('plasma'), norm=plt.Normalize(0.0, 1.0), linewidth=2): w = np.linspace(0.0, 1.0, len(x)) if not hasattr(w, "__iter__"): w = np.array([w]) w = np.asarray(w) segments = make_segments3(x, y, z) lc = mpl3d.Line3DCollection(segments, array=w, cmap=cm, norm=norm, linewidth=linewidth) return lc
def __init__(self, ax, cfg): d = cfg.animation.quad_size r = cfg.animation.rotor_size body_segs = np.array([ [[d, 0, 0], [0, 0, 0]], [[-d, 0, 0], [0, 0, 0]], [[0, d, 0], [0, 0, 0]], [[0, -d, 0], [0, 0, 0]] ]) colors = ( (1, 0, 0, 1), (0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 1, 1), ) self.body = art3d.Line3DCollection( body_segs, colors=colors, linewidths=2 ) kwargs = dict(radius=r, ec="k", fc="k", alpha=0.3) self.rotors = [ Circle((d, 0), **kwargs), Circle((0, d), **kwargs), Circle((-d, 0), **kwargs), Circle((0, -d), **kwargs), ] ax.add_collection3d(self.body) for rotor in self.rotors: ax.add_patch(rotor) art3d.pathpatch_2d_to_3d(rotor, z=0) self.body._base = self.body._segments3d for rotor in self.rotors: rotor._segment3d = np.array(rotor._segment3d) rotor._center = np.array(rotor._center + (0,)) rotor._base = rotor._segment3d
def colomapped_wireframe(plane, ax, stride, norm, colormap='hsv'): # Source: http://stackoverflow.com/a/24958192/5524090 wire = ax.plot_wireframe(X=plane.xx, Y=plane.yy, Z=plane.zz, rstride=stride, cstride=stride) # Retrieve data from internal storage of plot_wireframe, then delete it nx, ny, _ = np.shape(wire._segments3d) wire_x = np.array(wire._segments3d)[:, :, 0].ravel() wire_y = np.array(wire._segments3d)[:, :, 1].ravel() wire_z = np.array(wire._segments3d)[:, :, 2].ravel() wire.remove() # Create data for a LineCollection wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)]) wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)]) wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)]) to_delete = np.arange(0, nx * ny, ny) wire_x1 = np.delete(wire_x1, to_delete, axis=1) wire_y1 = np.delete(wire_y1, to_delete, axis=1) wire_z1 = np.delete(wire_z1, to_delete, axis=1) scalars = np.delete(wire_z, to_delete) segs = [ list(zip(xl, yl, zl)) for xl, yl, zl in zip(wire_x1.T, wire_y1.T, wire_z1.T) ] # Plot the wireframe by a line3DCollection my_wire = art3d.Line3DCollection(segs, cmap=colormap, norm=norm, linewidths=2.0) my_wire.set_array(scalars) ax.add_collection(my_wire) return my_wire
def create_polygon(zipped_list, ax, dict_color): lst_pt = zipped_list[0] color = np.random.rand( 3, ) if (not zipped_list[1]) else dict_color[zipped_list[1]] if (len(lst_pt) == 1): list_solo_x, list_solo_y, list_solo_z = [lst_pt[0][0] ], [lst_pt[0][1] ], [lst_pt[0][2]] ax.plot(list_solo_x, list_solo_y, list_solo_z, marker='o', linestyle="none", color=color) elif (len(lst_pt) == 2): ax.add_collection3d(art3d.Line3DCollection([lst_pt], color=color)) else: ax.add_collection3d( art3d.Poly3DCollection([lst_pt], facecolors=color, edgecolors="black", linewidths=1, linestyle="-", alpha=0.5))
def custom_wireframe(ax, X, Y, Z, *args, **kwargs): """ Overoad matplotlib's plot_wireframe for a special use case that we want to plot a wireframe over a surface with customizability of those lines. In future versions, this may be incorporated into matplotlib natively. This would still be required for backwards compatibility. """ rstride = kwargs.pop("rstride", 1) cstride = kwargs.pop("cstride", 1) ts = Z had_data = ax.has_data() Z = np.atleast_2d(Z) # FIXME: Support masked arrays X, Y, Z = np.broadcast_arrays(X, Y, Z) rows, cols = Z.shape # We want two sets of lines, one running along the "rows" of # Z and another set of lines running along the "columns" of Z. # This transpose will make it easy to obtain the columns. tX, tY, tZ = np.transpose(X), np.transpose(Y), np.transpose(Z) if rstride: rii = list(xrange(0, rows, rstride)) # Add the last index only if needed if rows > 0 and rii[-1] != (rows - 1): rii += [rows - 1] else: rii = [] if cstride: cii = list(xrange(0, cols, cstride)) if cols > 0 and cii[-1] != (cols - 1): cii += [cols - 1] else: cii = [] # If the inputs were empty, then just # reset everything. if Z.size == 0: rii = [] cii = [] xlines = [X[i] for i in rii] ylines = [Y[i] for i in rii] zlines = [Z[i] for i in rii] txlines = [tX[i] for i in cii] tylines = [tY[i] for i in cii] tzlines = [tZ[i] for i in cii] # Row lines from rowstrides lines = [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(xlines, ylines, zlines)] # Col lines form colstrides lines += [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(txlines, tylines, tzlines)] linec = art3d.Line3DCollection(lines, *args, **kwargs) ax.add_collection(linec) ax.auto_scale_xyz(X, Y, Z, had_data) if 'cmap' in kwargs: linec = wire_cmap(linec, ax, cmap=kwargs['cmap']) return linec
def harp_plot(harp_files, zdata, gif, png, show): import yaml import os # file Parsing ############################################################ trace_files = [] trace_file_lists = [] neural_net_files = [] train_file = [] print('\x1B[34m==> \x1B[0m Parsing Files') #TODO: if yaml files use an explicit file type key, parsing would be much simpler for fname in harp_files: print(fname) f = open(fname) if f.readline().startswith('%YAML'):# if YAML file docCount = f.read().count('---')#count number of documents f.seek(0) #return to start of stream if docCount == 1: yamlDoc = f.read(1000) if 'events' in yamlDoc: trace_files.append(fname) elif 'spatio-temporal-neuron-weights' in yamlDoc:# crbf neural net neural_net_files.append(fname) else: #multi doc yaml file, assume st training train_file.append(fname) else: # assume trace list text file trace_file_lists.append(fname)# add to trace data file list # display results print('\x1B[34m==> \x1B[0m Plotting') # matplotlib plot ######################################################### import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import axes3d, art3d # set font plt.rc('font', family = 'serif', serif = 'CMU Serif') #setup 3D subplot x,y = plt.figaspect(.75)*1.5 fig = plt.figure(figsize=(x,y), tight_layout=True) ax = fig.add_subplot(111, projection='3d') # set axes properties # ax.view_init(elev=40, azim=-115)#stc-3 ax.view_init(elev=36, azim=-70)#stc-2 ax.set_xlabel('x') ax.set_xlim(0, 1) ax.set_xticks([0, 0.5, 1]) ax.set_ylabel('y') ax.set_ylim(0, 1) ax.set_yticks([0, 0.5, 1]) if zdata: zidx = 2 ax.set_zlabel('z') ax.set_zlim3d(0, 1) ax.set_zticks([0, 0.5, 1]) else: zidx = 3 ax.set_zlabel('time') ax.set_zlim(0, 2*np.pi) ax.set_zticks([0, np.pi, 2*np.pi]) ax.set_zticklabels(['0', '$\pi$', '2$\pi$']) leg_art = [] leg_lable = [] if len(trace_files) > 0: print('normalized trace data') #load training trace date yaml file for trace in trace_files: print(trace) td = td_arrayfromyaml(trace) tdScatter = ax.scatter(td[:,0],td[:,1],td[:,zidx], s=10, c='grey', edgecolor='black', marker='o', depthshade=False, zorder=0, alpha=0.8) leg_art.append(tdScatter) leg_lable.append('Trace Data') # for trace in f.read().splitlines(): if len(trace_file_lists) > 0: print('normalized trace data groups') #load training trace date yaml file for trace_list in trace_file_lists: print(trace_list) if 'dom' in trace_list: eColor = 'red' label = 'dominant hand trace data' elif 'non' in trace_list: eColor = 'blue' label = 'non-dominant hand trace data' else: eColor = 'green' label = trace_list + ' trace data' for trace in open(trace_list).read().splitlines(): print(' ',trace) td = td_arrayfromyaml(trace) tdScatter = ax.scatter(td[:,0],td[:,1],td[:,zidx], s=10, c='grey', edgecolor=eColor, marker='o', depthshade=False, zorder=0, alpha=0.8) leg_art.append(tdScatter) leg_lable.append(label) frames = [] if len(train_file) > 0: print('Plotting neural network and links in...') print(train_file[0]) for yamlDoc in yaml.load_all(open(train_file[0])): stnw = np.array((yamlDoc['spatio-temporal-neuron-weights'][1:])) stnc = np.array((yamlDoc['spatio-temporal-neuron-edges'][1:])) links = np.array([np.vstack((stnw[cidx[0]], stnw[cidx[1]])).tolist() for cidx in stnc]) lc = art3d.Line3DCollection([[tuple(con[0,[0,1,zidx]]), tuple(con[1,[0,1,zidx]])] for con in links], lw=0.5) lc.set_color('coral') ntLines = ax.add_collection(lc) ntScatter = ax.scatter(stnw[:,0],stnw[:,1],stnw[:,zidx], s=30, c='crimson', edgecolor='coral', marker='o', depthshade=False) frames.append([ntLines,ntScatter]) leg_art.append((ntLines,ntScatter)) leg_lable.append('Spatio-temporal Neurons') elif len(neural_net_files) > 0: print('Plotting neural network and links...') for neural_net in neural_net_files: print(neural_net) yamlDoc = yaml.load(open(neural_net)) stnw = np.array((yamlDoc['spatio-temporal-neuron-weights'][1:])) stnc = np.array((yamlDoc['spatio-temporal-neuron-edges'][1:])) links = np.array([np.vstack((stnw[cidx[0]], stnw[cidx[1]])).tolist() for cidx in stnc]) lc = art3d.Line3DCollection([[tuple(con[0,[0,1,zidx]]), tuple(con[1,[0,1,zidx]])] for con in links], lw=0.5) lc.set_color('coral') nLines = ax.add_collection(lc) nScatter = ax.scatter(stnw[:,0],stnw[:,1],stnw[:,zidx], s=30, c='crimson', edgecolor='coral', marker='o', depthshade=False) leg_art.append((nLines,nScatter)) leg_lable.append('Spatio-temporal Neurons') legend = ax.legend(leg_art,leg_lable, fontsize='large', loc='lower right') legend.get_frame().set_edgecolor('darkgray') # ax.set_title('Spatio-temporal Layer Training') if len(frames) > 0: ani = animation.ArtistAnimation(fig, frames, interval=1500, repeat_delay=3000) if gif: if len(frames) > 0: ani.save('harp_plot.gif', writer='imagemagick') else: fig.savefig('harp_plot.gif') if png: if len(frames) > 0: ani.save('harp_plot.png', writer='imagemagick') else: fig.savefig('harp_plot.png') if show or not (gif or png): print('Showing plot') plt.show()
def plot(self, tree_inds: Union[int, List[int]] = None, view: str = None, colors: Union[Tuple[float, float, float, float], List[Tuple[float, float, float, float]], str] = None, unit: str = 'um', show: bool = True, ax: plt.axes = None): """ Generates a (3D) line plot of the trees contained in the skeleton object. Args: tree_inds (optional): Tree indices to be plotted. Default: All trees are plotted view (optional): Plot as 2D projection on orthonormal plane. Options: 'xy', 'xz', 'yz' Default: Plot as 3D projection colors (optional): Colors in which trees should be plotted. If only one RGBA tuple is specified, it is broadcasted over all trees. Alternatively, a list providing RGBA tuples for each tree can be passed. Lastly, the name of a mnatplotlib colormap (https://matplotlib.org/tutorials/colors/colormaps.html) can be passed as a str. Default: Skeleton colors (self.colors) are used unit (optional): Specifies in which unit the plot should be generated. Options: 'vx' (voxels), 'nm' (nanometer), 'um' (micrometer). Default: 'um' (micrometer) show (optional): Displays the plot in an interactive window. For repeatedly plotting on the same axes, set to False. Default: True ax: Axes to be plotted on. Returns: ax: Axes which was plotted on """ if tree_inds is None: tree_inds = list(range(len(self.nodes))) elif tree_inds is int: tree_inds = [tree_inds] if colors is None: colors = self.colors elif type(colors) is str: cmap = cm.get_cmap(colors) colors = [cmap(x) for x in np.linspace(0, 1, self.num_trees())] elif type(colors[0]) is not Sequence: colors = [colors] * self.num_trees() unit_factor = self._get_unit_factor(unit) allowed_views = ['xy', 'xz', 'yz'] if view is not None: assert (view in allowed_views), \ 'The passed view argument: {} is not among the allowed views: {}'.format(view, allowed_views) if ax is None: fig = plt.figure() if view is None: ax = fig.add_subplot(111, projection='3d') else: ax = fig.add_subplot(111, projection='rectilinear') else: if view is None: assert (ax.name == '3d'), \ 'To generate a 3D skeleton plot, the projection type of the passed axes must be 3D' else: assert (ax.name != '3d'), \ 'To generate a 2D skeleton plot, the projection type of the passed axes must be rectilinear' lims_min = [] lims_max = [] for tree_idx in tree_inds: edges = self.edges[tree_idx].copy() nodes = self.nodes[tree_idx].copy() if len(nodes) > 0: nodes['position'] = nodes['position'].multiply(unit_factor) if view == 'xy': nodes = nodes.drop([('position', 'z')], axis=1) elif view == 'xz': nodes = nodes.drop([('position', 'y')], axis=1) elif view == 'yz': nodes = nodes.drop([('position', 'x')], axis=1) lims_min.append(np.min(nodes['position'].values, axis=0)) lims_max.append(np.max(nodes['position'].values, axis=0)) segments = [] for edge in edges: n0 = nodes['position'][nodes.id == edge[0]].values[0] n1 = nodes['position'][nodes.id == edge[1]].values[0] segment = [[c for c in n0], [c for c in n1]] segments.append(segment) if view is None: line_collection = art3d.Line3DCollection( segments=segments, colors=colors[tree_idx]) ax.add_collection3d(line_collection) else: line_collection = LineCollection(segments=segments, colors=colors[tree_idx]) ax.add_collection(line_collection) lim_min = np.min(np.array(lims_min), axis=0) lim_max = np.max(np.array(lims_max), axis=0) ax.set_xlim(lim_min[0], lim_max[0]) ax.set_ylim(lim_min[1], lim_max[1]) if view is None: ax.set_zlim(lim_min[2], lim_max[2]) else: ax.set_aspect('equal') if show: plt.show() return ax
def plot_network_3d(self, ax=None, superjunction_signal=None, junction_signal=None, superjunction_stems=True, junction_stems=True, border=True, fill=True, base_line_kwargs={}, superjunction_stem_kwargs={}, junction_stem_kwargs={}, border_kwargs={}, fill_kwargs={}, orifice_kwargs={}, weir_kwargs={}, pump_kwargs={}): if ax is None: fig = plt.figure(figsize=(6, 6)) ax = fig.add_subplot(1, 1, 1, projection='3d') _map_x_j = self._map_x_j _map_y_j = self._map_y_j _x_Ik = self._x_Ik _dx_k = self._dx_k _kI = self._kI _J_uk = self._J_uk _J_dk = self._J_dk _Ik = self._Ik _Ip1k = self._Ip1k _z_inv_Ik = self._z_inv_Ik frac_pos = _x_Ik / _dx_k[_kI] _z_inv_j = self._z_inv_j if superjunction_signal is None: superjunction_signal = self.H_j - _z_inv_j if junction_signal is None: junction_signal = self.h_Ik _map_x_Ik = frac_pos * (_map_x_j[_J_dk] - _map_x_j[_J_uk])[_kI] + _map_x_j[_J_uk][_kI] _map_y_Ik = frac_pos * (_map_y_j[_J_dk] - _map_y_j[_J_uk])[_kI] + _map_y_j[_J_uk][_kI] collections = [] base = np.dstack([ np.column_stack([_map_x_Ik[_Ik], _map_x_Ik[_Ip1k]]), np.column_stack([_map_y_Ik[_Ik], _map_y_Ik[_Ip1k]]), np.column_stack([_z_inv_Ik[_Ik], _z_inv_Ik[_Ip1k]]) ]) lc_z = art3d.Line3DCollection(base, **base_line_kwargs) ax.add_collection3d(lc_z) collections.append(lc_z) if self.n_o: _J_uo = self._J_uo _J_do = self._J_do lines = np.dstack([ np.column_stack([_map_x_j[_J_uo], _map_x_j[_J_do]]), np.column_stack([_map_y_j[_J_uo], _map_y_j[_J_do]]), np.column_stack([_z_inv_j[_J_uo], _z_inv_j[_J_do]]) ]) lc_o = art3d.Line3DCollection(lines, **orifice_kwargs) ax.add_collection3d(lc_o) collections.append(lc_o) if self.n_w: _J_uw = self._J_uw _J_dw = self._J_dw lines = np.dstack([ np.column_stack([_map_x_j[_J_uw], _map_x_j[_J_dw]]), np.column_stack([_map_y_j[_J_uw], _map_y_j[_J_dw]]), np.column_stack([_z_inv_j[_J_uw], _z_inv_j[_J_dw]]) ]) lc_w = art3d.Line3DCollection(lines, **weir_kwargs) ax.add_collection3d(lc_w) collections.append(lc_w) if self.n_p: _J_up = self._J_up _J_dp = self._J_dp lines = np.dstack([ np.column_stack([_map_x_j[_J_up], _map_x_j[_J_dp]]), np.column_stack([_map_y_j[_J_up], _map_y_j[_J_dp]]), np.column_stack([_z_inv_j[_J_up], _z_inv_j[_J_dp]]) ]) lc_p = art3d.Line3DCollection(lines, **pump_kwargs) ax.add_collection3d(lc_p) collections.append(lc_p) if superjunction_stems: stems = np.dstack([ np.column_stack([_map_x_j, _map_x_j]), np.column_stack([_map_y_j, _map_y_j]), np.column_stack([_z_inv_j, _z_inv_j + superjunction_signal]) ]) st_j = art3d.Line3DCollection(stems, **superjunction_stem_kwargs) ax.add_collection3d(st_j) collections.append(st_j) if junction_stems: stems = np.dstack([ np.column_stack([_map_x_Ik, _map_x_Ik]), np.column_stack([_map_y_Ik, _map_y_Ik]), np.column_stack([_z_inv_Ik, _z_inv_Ik + junction_signal]) ]) st_h = art3d.Line3DCollection(stems, **junction_stem_kwargs) ax.add_collection3d(st_h) collections.append(st_h) if border: border_lines = np.dstack([ np.column_stack([_map_x_Ik[_Ik], _map_x_Ik[_Ip1k]]), np.column_stack([_map_y_Ik[_Ik], _map_y_Ik[_Ip1k]]), np.column_stack([ _z_inv_Ik[_Ik] + junction_signal[_Ik], _z_inv_Ik[_Ip1k] + junction_signal[_Ip1k] ]) ]) lc_h = art3d.Line3DCollection(border_lines, **border_kwargs) ax.add_collection3d(lc_h) collections.append(lc_h) if fill: poly = np.dstack([ np.column_stack([ _map_x_Ik[_Ik], _map_x_Ik[_Ik], _map_x_Ik[_Ip1k], _map_x_Ik[_Ip1k] ]), np.column_stack([ _map_y_Ik[_Ik], _map_y_Ik[_Ik], _map_y_Ik[_Ip1k], _map_y_Ik[_Ip1k] ]), np.column_stack([ _z_inv_Ik[_Ik], _z_inv_Ik[_Ik] + junction_signal[_Ik], _z_inv_Ik[_Ip1k] + junction_signal[_Ip1k], _z_inv_Ik[_Ip1k] ]) ]) poly_h = art3d.Poly3DCollection(poly, **fill_kwargs) ax.add_collection3d(poly_h) collections.append(poly_h) ax.set_xlim3d(_map_x_j.min(), _map_x_j.max()) ax.set_ylim3d(_map_y_j.min(), _map_y_j.max()) ax.set_zlim3d( min((_z_inv_Ik + junction_signal).min(), (_z_inv_j + superjunction_signal).min()), max((_z_inv_Ik + junction_signal).max(), (_z_inv_j + superjunction_signal).max())) return collections
def plot3d( self, color_mode: Optional[str] = None, with_mesh: bool = False, mesh_flattened: bool = False, axes_visible: bool = True, export: bool = False, show: bool = True, ) -> None: """A matplotlib-based 3d visualization. :param color_mode: Colormapping of specific attributes: 'by_height' - color filament edges accorging to z-position 'by_age' - color filament edges according to the node age. other - red. :param with_mesh: include plasma membrane mesh to denote internal volume of the cell. :param mesh_flattened: if True, show only xy projection of the mesh as a background at z = 0. :param axes_visible: Show or hide the figure axes and title. :param export: If True, export the figure in svg format. :param show: If True, display the figure. """ import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.art3d as art3d # Turn interactive plotting off. plt.ioff() fig = plt.figure(figsize=(10, 10)) fig.subplots_adjust(left=0, right=1, bottom=0, top=1) ax = fig.gca(projection='3d', proj_type='ortho') if axes_visible: fig.suptitle(self.figtitle3d) labels = self.len_units ax.set_xlabel('x (' + labels + ')') ax.set_ylabel('y (' + labels + ')') ax.set_zlabel('z (' + labels + ')') else: ax.set_axis_off() ax.xaxis.pane.fill = False ax.yaxis.pane.fill = False ax.zaxis.pane.fill = False ax.grid(False) axlim = [ 1.1 * self.plasma_membrane.min_.min(), 1.1 * self.plasma_membrane.max_.max() ] ax.set_xlim3d(axlim[0], axlim[1]) ax.set_ylim3d(axlim[0], axlim[1]) ax.set_zlim3d(axlim[0], axlim[1]) # 0., 2. * axlim) ax.view_init(azim=0, elev=90) if with_mesh: if mesh_flattened: mvs = np.copy(self.plasma_membrane.mesh.points) mvs[:, 2] = 0. else: mvs = self.plasma_membrane.mesh.points mvs = [ mvs[c, :] for c in self.plasma_membrane.mesh.cells_dict['triangle'] ] p = art3d.Poly3DCollection(mvs, zsort='min', edgecolor=None, facecolor=(0.9, 0.9, 0.9, 0.2)) ax.add_collection3d(p) if color_mode == 'by_height': pp = [m.reshape(-1, 1, 3) for m in self.pos] segs = np.concatenate( [np.concatenate([m[:-1], m[1:]], axis=1) for m in pp]) cc = np.concatenate([m[:-1, 2] for m in self.pos]) norm = plt.Normalize(self.plasma_membrane.min_[2], self.plasma_membrane.max_[2]) c = [(n, 0., 1. - n) for n in norm(cc)] coll = art3d.Line3DCollection(segs, colors=c, lw=0.3) ax.add_collection(coll) # fig.colorbar(coll, ax=ax) elif color_mode == 'by_age': pp = [m.reshape(-1, 1, 3) for m in self.pos] segs = np.concatenate( [np.concatenate([m[:-1], m[1:]], axis=1) for m in pp]) cc = np.concatenate([a[:-1] for a in self.ages]) c = plt.cm.jet(cc / cc.max()) coll = art3d.Line3DCollection(segs, colors=c, lw=0.3) ax.add_collection(coll) else: for m in self.pos: ax.plot(m[:, 0], m[:, 1], m[:, 2], c='r', lw=0.3) if export: self.export_to_svg(color_mode) if show: plt.show() else: plt.close(fig)
# create data for a LineCollection wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)]) wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)]) wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)]) to_delete = np.arange(0, nx * ny, ny) wire_x1 = np.delete(wire_x1, to_delete, axis=1) wire_y1 = np.delete(wire_y1, to_delete, axis=1) wire_z1 = np.delete(wire_z1, to_delete, axis=1) scalars = np.delete(wire_z, to_delete) segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(wire_x1.T, wire_y1.T, wire_z1.T)] # Plots the wireframe by a a line3DCollection my_wire = art3d.Line3DCollection(segs, cmap="hsv") my_wire.set_array(scalars) ax.add_collection(my_wire) plt.colorbar(my_wire) plt.show() # ukazi.m:226 -- Note: Not implemented. Same chart as previous section. B = np.double(A[:, :, 1]) X, Y = np.meshgrid(np.arange(100), np.arange(100)) Z = abs(np.fft.fft2(B - np.mean(np.ravel(B)))[0:100, 0:100]) colors = cm.Blues(Z) rcount, ccount, _ = colors.shape fig = plt.figure() fig.set_size_inches(7, 7)
def get_arrow(self, tail, head, length=1, arrow_length_ratio=.3, normalize=False, nargout=1, **kwargs): def calc_arrow(uvw, angle=15): """ To calculate the arrow head. uvw should be a unit vector. We normalize it here: """ # get unit direction vector perpendicular to (u,v,w) norm = np.linalg.norm(uvw[:2]) if norm > 0: x = uvw[1] / norm y = -uvw[0] / norm else: x, y = 0, 1 # compute the two arrowhead direction unit vectors ra = np.radians(angle) c = np.cos(ra) s = np.sin(ra) # construct the rotation matrices Rpos = np.array([[c + (x**2) * (1 - c), x * y * (1 - c), y * s], [y * x * (1 - c), c + (y**2) * (1 - c), -x * s], [-y * s, x * s, c]]) # opposite rotation negates all the sin terms Rneg = Rpos.copy() Rneg[[0, 1, 2, 2], [2, 2, 0, 1]] = -Rneg[[0, 1, 2, 2], [2, 2, 0, 1]] # multiply them to get the rotated vector return Rpos.dot(uvw), Rneg.dot(uvw) assert tail.size == 3 and head.size == 3 shaft_dt = np.linspace(0, length, num=2) arrow_dt = shaft_dt * arrow_length_ratio shaft_dt -= length XYZ = tail.reshape(1, 3) UVW = head.reshape(1, 3).astype(float) # Normalize rows of UVW norm = np.linalg.norm(UVW, axis=1) # If any row of UVW is all zeros, don't make a quiver for it mask = norm > 0 XYZ = XYZ[mask] if normalize: UVW = UVW[mask] / norm[mask].reshape((-1, 1)) else: UVW = UVW[mask] if len(XYZ) > 0: # compute the shaft lines all at once with an outer product shafts = (XYZ - np.multiply.outer(shaft_dt, UVW)).swapaxes(0, 1) # compute head direction vectors, n heads by 2 sides by 3 dimensions head_dirs = np.array([calc_arrow(d) for d in UVW]) # compute all head lines at once, starting from where the shaft ends heads = shafts[:, :1] - np.multiply.outer(arrow_dt, head_dirs) # stack left and right head lines together heads.shape = (len(arrow_dt), -1, 3) # transpose to get a list of lines heads = heads.swapaxes(0, 1) """ Rodrigues' rotation so that we can project the heads to x-y plane properly """ # Get the vector representation of the shaft # notice that the convention is reversed k = shafts[0, 0, :] - shafts[0, 1, :] if not np.allclose(np.linalg.norm(k), 0): k = k / np.linalg.norm(k) # Cross-product matrix K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]]) theta = np.pi / 2 R = np.eye(3) + K * np.sin(theta) + (K @ K * (1 - np.cos(theta))) else: R = np.eye(3) for idx in range(2): # Shift to origin and after rotation shift it back to the original # reference point. heads[idx, :, :] = ( (heads[idx, :, :] - shafts[0, 1, :]) @ R.T) + shafts[0, 1, :] lines = [*shafts, *heads] else: lines = [] arrow = art3d.Line3DCollection(lines, **kwargs) if nargout == 1: return arrow elif nargout == 2: return arrow, XYZ
def update(self): self.fig3d.cla() self.fig3d.set_title('3D World') self.fig3d.set_xlabel('x-axis') self.fig3d.set_ylabel('y-axis') self.fig3d.set_zlabel('z-axis') self.fig3d.set_xlim([-3, 3]) self.fig3d.set_ylim([-3, 3]) self.fig3d.set_zlim([0, 8]) cam = self.cam obj = self.obj objPoints = self.obj.getPoints3d() a = [self.fig3d] arrow_length = 1.5 p = [] p.append(np.mean(self.obj.getPoints3d()[0, :])) p.append(np.mean(self.obj.getPoints3d()[1, :])) p.append(np.mean(self.obj.getPoints3d()[2, :])) if obj.isSTL(): self.fig3d.set_xlim([-50, 50]) self.fig3d.set_ylim([-50, 50]) self.fig3d.set_zlim([0, 100]) obj_mesh = deepcopy(obj.mesh) obj_mesh.transform(obj.getExtrinsicMatrix()) # Get the vectors that define the triangular faces that form the 3D object kong_vectors = obj_mesh.vectors # Plot and render the faces of the object self.fig3d.add_collection3d(art3d.Poly3DCollection(kong_vectors)) # Plot the contours of the faces of the object self.fig3d.add_collection3d( art3d.Line3DCollection(kong_vectors, colors='k', linewidths=0.2, linestyles='-')) # Set axes and their aspect self.fig3d.auto_scale_xyz(objPoints[0, :], objPoints[1, :], objPoints[2, :]) arrow_length = 100 # Plotting object arrows Transforms.draw_arrows(p, obj.getBaseMatrix(), a, length=arrow_length) # Plot the vertices of the object self.fig3d.plot3D(objPoints[0, :], objPoints[1, :], objPoints[2, :], 'k.') # Transforms.set_axes_equal(self.fig3d) p = [] p.append(cam.getPoints3d()[0]) p.append(cam.getPoints3d()[1]) p.append(cam.getPoints3d()[2]) # Plotting camera arrows camPoints = cam.getPoints3d() Transforms.draw_arrows(p, cam.getBaseMatrix(), a, length=arrow_length / 5) self.fig3d.plot3D(camPoints[0, :], camPoints[1, :], camPoints[2, :], 'k.') # Projection self.figProjection.cla() self.figProjection.set_title("Camera View") self.figProjection.set_xlabel("x-axis") self.figProjection.set_ylabel("y-axis") self.figProjection.set_xlim([-2, 2]) self.figProjection.set_ylim([-1, 1]) self.figProjection.set_aspect('equal') obj2Cam = np.dot(np.linalg.inv(cam.getExtrinsicMatrix()), obj.getPoints3d()) projection = np.dot(Transforms.newProjectionMatrix(), obj2Cam) projection = np.dot(cam.getIntrinsicMatrix(), projection) indexes = projection[2, :] > 0 # print(idx.shape) projection = projection[:, indexes] Z = projection[2] projection /= Z self.figProjection.plot(projection[0], projection[1], 'k.') self.fig.canvas.draw()
def plot_result_b(self): x1_ = np.zeros([self.xn1b, self.xn2b]) x2_ = np.zeros([self.xn1b, self.xn2b]) fuzzy_fx = np.zeros([self.xn1b, self.xn2b]) x1 = Symbol('x1') x2 = Symbol('x2') for i in range(self.xn1b): for j in range(self.xn2b): # x x1_[i,j] = self.fire_Ax1b[i] x2_[i,j] = self.fire_Ax2b[j] # membership tmp_x1 = int(np.where(self.xb1_range == self.fire_Ax1b[i])[0]) tmp_x2 = int(np.where(self.xb2_range == self.fire_Ax2b[j])[0]) Ai1 = self.Ax1b[i][tmp_x1] Aj2 = self.Ax2b[j][tmp_x2] # f(x) if self.fg: fuzzy_fx[i,j] = (f(self.fg, self.fire_Ax1b[i], self.fire_Ax2b[j]) * Ai1 * Aj2) / (Ai1*Aj2) else: fuzzy_fx[i,j] = (fx(self.fire_Ax1b[i],self.fire_Ax2b[j])*Ai1*Aj2) / (Ai1*Aj2) fig = plt.figure() ax = fig.gca(projection='3d') wire = ax.plot_wireframe(x1_, x2_, fuzzy_fx, rstride=5, cstride=5) # Retrive data from internal storage of plot_wireframe, then delete it nx, ny, _ = np.shape(wire._segments3d) wire_x = np.array(wire._segments3d)[:, :, 0].ravel() wire_y = np.array(wire._segments3d)[:, :, 1].ravel() wire_z = np.array(wire._segments3d)[:, :, 2].ravel() wire.remove() # create data for a LineCollection wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)]) wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)]) wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)]) to_delete = np.arange(0, nx*ny, ny) wire_x1 = np.delete(wire_x1, to_delete, axis=1) wire_y1 = np.delete(wire_y1, to_delete, axis=1) wire_z1 = np.delete(wire_z1, to_delete, axis=1) scalars = np.delete(wire_z, to_delete) segs = [list(zip(xl, yl, zl)) for xl, yl, zl in zip(wire_x1.T, wire_y1.T, wire_z1.T)] # Plots the wireframe by a a line3DCollection my_wire = art3d.Line3DCollection(segs, cmap="hsv") my_wire.set_array(scalars) ax.add_collection(my_wire) plt.colorbar(my_wire) ax.set_xlabel('x1') ax.set_ylabel('x2') ax.set_zlabel('g(x1,x2)') #ax.legend() plt.show()
def overload_plot_wireframe(ax, X, Y, Z, *args, **kwargs): ''' Overoad matplotlib's plot_wireframe for a special use-case. In future versions, this may be incorporated into matplotlib natively. This would still be required for backwards compatibility. ''' rstride = kwargs.pop("rstride", 1) cstride = kwargs.pop("cstride", 1) ts = Z had_data = ax.has_data() Z = np.atleast_2d(Z) # FIXME: Support masked arrays X, Y, Z = np.broadcast_arrays(X, Y, Z) rows, cols = Z.shape # We want two sets of lines, one running along the "rows" of # Z and another set of lines running along the "columns" of Z. # This transpose will make it easy to obtain the columns. tX, tY, tZ = np.transpose(X), np.transpose(Y), np.transpose(Z) if rstride: rii = list(xrange(0, rows, rstride)) # Add the last index only if needed if rows > 0 and rii[-1] != (rows - 1): rii += [rows - 1] else: rii = [] if cstride: cii = list(xrange(0, cols, cstride)) if cols > 0 and cii[-1] != (cols - 1): cii += [cols - 1] else: cii = [] # If the inputs were empty, then just # reset everything. if Z.size == 0: rii = [] cii = [] xlines = [X[i] for i in rii] ylines = [Y[i] for i in rii] zlines = [Z[i] for i in rii] txlines = [tX[i] for i in cii] tylines = [tY[i] for i in cii] tzlines = [tZ[i] for i in cii] # Row lines from rowstrides lines = [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(xlines, ylines, zlines)] # Col lines form colstrides lines += [list(zip(xl, yl, zl)) for xl, yl, zl in \ zip(txlines, tylines, tzlines)] #allzlines = np.concatenate([np.array(zlines).ravel(), #np.array(tzlines).ravel()]) #allxlines = np.concatenate([np.array(xlines).ravel(), #np.array(txlines).ravel()]) #allylines = np.concatenate([np.array(ylines).ravel(), #np.array(tylines).ravel()]) #ALL = np.concatenate([allzlines, allxlines, allylines]) #test = np.array(list(ts.columns.values.ravel()) + #list(ts.index.values.ravel().ravel())) # kwargs = {} #REMOVE ME HACK linec = art3d.Line3DCollection(lines, *args, **kwargs) #linec.set_array(test) #linec.set_cmap('jet_r') #linec.set_clim(0,2500) ax.add_collection(linec) ax.auto_scale_xyz(X, Y, Z, had_data) return linec
def plot_edges(ax, G, nodes): lines = [(nodes[edge[0]], nodes[edge[1]]) for edge in G.edges] lc = art3d.Line3DCollection(lines, colors='black', linewidths=1) ax.add_collection(lc)