def __init__(self, f, xmin=-1, xmax=1, ymin=-1, ymax=1, precision=50, is3d=False, newfig=True, colorbar=False, cblabel=None): """ :key precision: how many steps along every dimension """ if isinstance(f, FunctionEnvironment): assert f.xdim == 2 self.f = lambda x, y: f(array([x, y])) elif isclass(f) and issubclass(f, FunctionEnvironment): tmp = f(2) self.f = lambda x, y: tmp(array([x, y])) else: self.f = f self.precision = precision self.is3d = is3d self.colorbar = colorbar self.cblabel = cblabel self.xs = r_[xmin:xmax:self.precision * 1j] self.ys = r_[ymin:ymax:self.precision * 1j] self.zs = self._generateValMap() if newfig or self.is3d: self.fig = figure() if self.is3d: import matplotlib.axes3d as p3 self.fig = p3.Axes3D(self.fig) #@UndefinedVariable
def _plot3D(cls, plot_var_value_ls, plot_var_name_ls, output_fname_prefix, picker_function=on_click_showing_passingdata): import pylab import matplotlib.axes3d as p3 pylab.clf() fig = pylab.figure() fig.canvas.mpl_connect('pick_event', picker_function) ax = p3.Axes3D(fig) # plot3D requires a 1D array for x, y, and z # ravel() converts the 100x100 array into a 1x10000 array #ax.plot3D(plot_var_value_ls[0], plot_var_value_ls[1], plot_var_value_ls[2]) ax.scatter3D(plot_var_value_ls[0], plot_var_value_ls[1], plot_var_value_ls[2], picker=5) ax.set_xlabel(plot_var_name_ls[0]) ax.set_ylabel(plot_var_name_ls[1]) ax.set_zlabel(plot_var_name_ls[2]) #fig.add_axes(ax) pylab.savefig('%s.png' % output_fname_prefix, dpi=100) pylab.savefig('%s.svg' % output_fname_prefix, dpi=100) pylab.show()
def wireframeDrawAgent(self, method, fig=None): import matplotlib.axes3d as p3 if fig == None: fig = figure() ax = p3.Axes3D(fig) def do(pos, p): if len(pos) < 2: return None figure(fig.number) x, y, z = method(array(pos).transpose()) if p: #p._x=x #p._y=y #p._y=z #draw() #cla() gca().collections.remove(p) p = ax.plot_wireframe(x, y, z) show() else: p = ax.plot_wireframe(x, y, z) show() figure(self.fig.number) return p return do
def mplot3d(f, var1, var2, show=True): """ Plot a 3d function using matplotlib/Tk. """ import warnings warnings.filterwarnings("ignore", "Could not match \S") try: import pylab as p import matplotlib.axes3d as p3 except ImportError: raise ImportError("Matplotlib is required to use mplot3d.") x, y, z = sample(f, var1, var2) fig = p.figure() ax = p3.Axes3D(fig) #ax.plot_surface(x,y,z) #seems to be a bug in matplotlib ax.plot_wireframe(x, y, z) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') if show: p.show()
def setData(self, data, current=None): try: if self.__initialise: # u and v are parametric variables. # u is an array from 0 to 2*pi, with 100 elements u = r_[0:2 * pi:100j] # v is an array from 0 to 2*pi, with 100 elements v = r_[0:pi:100j] # x, y, and z are the coordinates of the points for plotting # each is arranged in a 100x100 array self.__x = 10 * outer(cos(u), sin(v)) self.__y = 10 * outer(sin(u), sin(v)) self.__z = 10 * outer(ones(size(u)), cos(v)) self.__fig = p.figure() self.__ax = p3.Axes3D(self.__fig) self.__ax.plot_wireframe(self.__x, self.__y, self.__z) self.__initialise = 0 if self.__i: self.__ax.set_xlabel( 'alternating labels to show incoming data') self.__i = 0 else: self.__ax.set_xlabel('') self.__i = 1 # redraw the plot p.draw() except: raise "Something went wrong when setData was called"
def plot_data(summary, outliers): """ REDUNDANT (more or less)""" #relmag = clip(data['mag3']/data['Vmag'], 0, 20) summary[:, 0] = from_deg(summary[:, 0]) X, Y = from_polar(summary['AVGR'], summary['ANGLE']) X += c_x Y += c_y out_X, out_Y = from_polar(outliers['r'], outliers['theta']) out_X += c_x out_Y += c_y fig = figure() ax = p3.Axes3D(fig) #ax.scatter3D(data['X'], data['Y'], relmag, c=relmag) #ax.scatter3D(data['X'], data['Y'], relmag, c=data['time']) #ax.scatter3D(out_X, out_Y, outliers[:,0], c=outliers[:,3]) ax.scatter3D(outliers['time'], out_X, out_Y, c=outliers['mag3']) #ax.plot3D(X, Y, summary[:,2], c='k')#, c=summary[:,2]) #ax.plot3D(X, Y, summary[:,2] + 2.5*summary[:,3], c='r') #, c=summary[:,2]) #ax.plot3D(X, Y, summary[:,2] - 2.5*summary[:,3], c='r')#, c=summary[:,2]) #scatter(data[2], data[3], c=relmag, faceted=False) show()
def scatter3dDrawAgent(self, method, fig=None): import matplotlib.axes3d as p3 if fig == None: fig = figure() ax = p3.Axes3D(fig) def do(pos, p): if len(pos) < 2: return None figure(fig.number) x, y, z = method(array(pos).transpose()) if p: #p._x=ravel(x) #p._y=ravel(y) #p._y=ravel(z) #draw() #cla() gca().collections.remove(p._wrapped) del p p = ax.scatter3D(ravel(x), ravel(y), ravel(z)) show() else: p = ax.scatter3D(ravel(x), ravel(y), ravel(z)) show() figure(self.fig.number) return p return do
def plotCurves(self, showSamples=False, force2D=True): from pylab import clf, hold, plot, fill, title, gcf, pcolor, gray if not self.calculated: self._calculate() if self.indim == 1: clf() hold(True) if showSamples: # plot samples (gray) for _ in range(5): plot(self.testx, self.pred_mean + random.multivariate_normal( zeros(len(self.testx)), self.pred_cov), color='gray') # plot training set plot(self.trainx, self.trainy, 'bx') # plot mean (blue) plot(self.testx, self.pred_mean, 'b', linewidth=1) # plot variance (as "polygon" going from left to right for upper half and back for lower half) fillx = r_[ravel(self.testx), ravel(self.testx[::-1])] filly = r_[self.pred_mean + 2 * diag(self.pred_cov), self.pred_mean[::-1] - 2 * diag(self.pred_cov)[::-1]] fill(fillx, filly, facecolor='gray', edgecolor='white', alpha=0.3) title('1D Gaussian Process with mean and variance') elif self.indim == 2 and not force2D: from matplotlib import axes3d as a3 fig = gcf() fig.clear() ax = a3.Axes3D(fig) #@UndefinedVariable # plot training set ax.plot3D(ravel(self.trainx[:, 0]), ravel(self.trainx[:, 1]), ravel(self.trainy), 'ro') # plot mean (x, y, z) = [ m.reshape(sqrt(len(m)), sqrt(len(m))) for m in (self.testx[:, 0], self.testx[:, 1], self.pred_mean) ] ax.plot_wireframe(x, y, z, colors='gray') return ax elif self.indim == 2 and force2D: # plot mean on pcolor map gray() # (x, y, z) = map(lambda m: m.reshape(sqrt(len(m)), sqrt(len(m))), (self.testx[:,0], self.testx[:,1], self.pred_mean)) m = floor(sqrt(len(self.pred_mean))) pcolor(self.pred_mean.reshape(m, m)[::-1, :]) else: print("plotting only supported for indim=1 or indim=2.")
def plotQpoints(): """Plots the Qpoints used for phonon calculation.""" import pylab as pl import matplotlib.axes3d as p3 qpoints, weights = parseQpoints() fig = pl.figure() ax = p3.Axes3D(fig) ax.scatter3D(qpoints[:, 0], qpoints[:, 1], qpoints[:, 2]) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') pl.show()
def plot_outlier_spiral(outliers): """ Plot x vs y vs time for a set of outliers. Colour points by mag3. """ out_X, out_Y = from_polar(outliers['r'], outliers['theta']) out_X += c_x out_Y += c_y fig = figure() ax = p3.Axes3D(fig) #ax.scatter3D(outliers['time'], out_X, out_Y, c=outliers['mag3']) ax.scatter3D(outliers['time'], out_X, out_Y, c=outliers['time']) show()
def plotQpoints(qpoints): """Plots the q-points used for phonon calculation. The q-points can be parsed from the Phon output with: >>> qpoints, weights = parseQpoints(filename='QPOINTS')""" import pylab as pl import matplotlib.axes3d as p3 fig = pl.figure() ax = p3.Axes3D(fig) ax.scatter3D(qpoints[:,0],qpoints[:,1],qpoints[:,2]) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') pl.show()
def plot_particles(particles, name_of_the_figure): if HAS_MATPLOTLIB: print "plotting the data" figure = pyplot.figure(figsize=(40, 40)) plots = map(lambda x: figure.add_subplot(4, 4, x + 1), range(4 * 4)) index = 0 for data in particles.history: if index > 15: break x_values = data.x.value_in(units.parsec) y_values = data.y.value_in(units.parsec) mass_values = data.mass.value_in(units.MSun) sizes = mass_values * 10.0 plots[index].scatter(x_values, y_values, marker='o', s=sizes) index += 1 for plot in plots: plot.set_xlim(-2.0, 2.0) plot.set_ylim(-2.0, 2.0) figure.savefig(name_of_the_figure) if False: from matplotlib import axes3d figure = pyplot.figure() axes_3d = axes3d.Axes3D(figure) positions = particles.get_values_of_attribute('position') xs = numpy.array([ position.x.value_in(units.lightyear) for position in positions ]) ys = numpy.array([ position.y.value_in(units.lightyear) for position in positions ]) zs = numpy.array([ position.z.value_in(units.lightyear) for position in positions ]) # print xs, yz, zs plot = axes_3d.scatter(xs, ys, zs) axes_3d.set_xlim(-10.0, 10.0) axes_3d.set_ylim(-10.0, 10.0) axes_3d.set_zlim(-10.0, 10.0) figure.savefig("3d_" + name_of_the_figure)
def Hem_scatter(x, y, z, t=None, cmap=pylab.cm.jet): fig = pylab.figure() ax = axes3d.Axes3D(fig) if t == None: ax.scatter3D(x, y, z) else: ax.scatter3D(x, y, z, c=t, cmap=cmap) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_zlim(0, 2) # elev, az ax.view_init(10, -80)
def _plot3D(self, star, data): fig = p.figure(1) if fig.axes: ax = fig.axes[0] else: ax = p3.Axes3D(fig) ax.set_xlabel(self.x) ax.set_ylabel(self.y) ax.set_zlabel(self.z) #print data c, s = self._getcs(data) #print "plotting" ax.scatter3D(data[self.x], data[self.y], data[self.z], c=c, s=s, faceted=False)
def _test_plot(): try: import pylab except ImportError: pylab = False if pylab: pylab.ion() import matplotlib.axes3d as p3 # Create points u = r_[0:2 * pi:100j] v = r_[0:pi:100j] x = 10 * outer(cos(u), sin(v)) y = 10 * outer(sin(u), sin(v)) z = 10 * outer(ones(size(u)), cos(v)) points = transpose(vstack((x.flat, y.flat, z.flat))) hull_ = asarray([(0, 0, 0), (0, 0, 1), (-10, 0, 0), (-10, 0, 1), (-10, -10, 0), (-10, -10, 1), (0, -10, 0), (0, -10, 1)]) # Plot full surface ax = p3.Axes3D(pylab.figure()) ax.plot_surface(x, y, z) # Plot slice/hull x_, y_, z_ = map(squeeze, hsplit(hull_, 3)) ax.scatter3d(x_, y_, z_, color='g') s = nonzero(z_ == 0) x, y, z = x_[s].tolist(), y_[s].tolist(), z_[s].tolist() x.append(x[0]) y.append(y[0]) z.append(z[0]) ax.plot3D(x, y, z, 'g-') ax.plot3D(x, y, ones(len(z)), 'g-') # Plot overlap x, y, z = map(squeeze, hsplit(points[nonzero(inside(hull_, points))], 3)) ax.scatter3d(x, y, z, color='r') pylab.draw() pylab.savefig('hull3d.png')
def trplot(r, name=''): ''' Plot a rotation as a set of axes aligned with the x, y and z directions of a frame rotated by C{r}. ''' if type(r) is matrix: q = quaternion(r) elif isinstance(r, quaternion): q = r else: raise ValueError x = q * mat([1, 0, 0]) y = q * mat([0, 1, 0]) z = q * mat([0, 0, 1]) fig = p.figure() ax = p3.Axes3D(fig) ax.plot3d([0, x[0, 0]], [0, x[0, 1]], [0, x[0, 2]], color='red') ax.plot3d([0, y[0, 0]], [0, y[0, 1]], [0, y[0, 2]], color='green') ax.plot3d([0, z[0, 0]], [0, z[0, 1]], [0, z[0, 2]], color='blue') p.show()
ax.set_ylabel('y') ax.set_zlabel('z') # elev, az ax.view_init(10, -80) n, k = 1000, 15 x, y, z, t = s_distr(n, hole=False) data = mdp.numx.array([x, y, z]).T lle_projected_data = mdp.nodes.LLENode(k, output_dim=2)(data) #plot input in 3D fig = pylab.figure(1, figsize=(6, 4)) pylab.clf() ax = axes3d.Axes3D(fig) ax.scatter3D(x, y, z, c=t, cmap=pylab.cm.jet) ax.set_xlim(-2, 2) ax.view_init(10, -80) pylab.draw() pylab.savefig('s_shape_3D.png') #plot projection in 2D pylab.clf() projection = lle_projected_data pylab.scatter(projection[:,0],\ projection[:,1],\ c=t,cmap=pylab.cm.jet) pylab.savefig('s_shape_lle_proj.png') # ### with hole
def print_accessibility(self,threshold=0.15,access='total'): '''Plot the influence of the accessibility on dielectric constant It does it only for residues which nrmsd is below the threshold''' if access=='total': colomn=-3 elif access=='backbone': colomn=-2 elif access=='side chain': colomn=-1 else: print print 'Usage: accessibility could take only following values:' print 'total' print 'background' print 'side chain' os._exit(0) dir_name=os.path.join(os.getcwd(),'figures/') file_name='%saccessibility_%s.out' %(dir_name,self.pdb) if not os.path.isfile(file_name): self.accessibility() if not os.path.isdir(os.path.join(os.getcwd(),'figures/')): os.system('mkdir figures') dir_name=os.path.join(os.getcwd(),'figures/') fd=open('%saccessibility_%s.out' %(dir_name,self.pdb),'r') lines=fd.readlines() fd.close() acc_total={} acc_side={} acc_back={} plot2D={} plot2D_1={} for line in lines: line=string.strip(line) num=string.split(line)[3] residue='A:'+string.zfill(num,4) acc_total[residue]=float(string.split(line)[-3]) acc_back[residue]=float(string.split(line)[-2]) acc_side[residue]=float(string.split(line)[-1]) for residue in self.residues: if (residue in self.ultimate_distance.keys()) and (self.ultimate_distance[residue]<=threshold): if access=='total': acc=acc_total[residue] elif access=='backbone': acc=acc_back[residue] elif access=='side chain': acc=acc_side[residue] plot2D[acc]=self.ultimate_diel[residue] if self.ultimate_distance[residue]<=threshold/2: plot2D_1[acc]=self.ultimate_diel[residue] clf() figure(num=1,dpi=400,figsize=(10,5),frameon=False) grid(True) hold(True) xlabel('%s access.[A^2]'%access) ylabel('effective dielectric constant') plot(plot2D.keys(),plot2D.values(),'bo',label='%4s<NRMSD<=%4s'%(str(threshold/2),str(threshold))) plot(plot2D_1.keys(),plot2D_1.values(),'ro',label='NRMSD<=%4s'%str(threshold/2)) file_name=dir_name+'%s_accessibility_vs_diel.png'%access legend() savefig(file_name) #3D plot X=[] Y=[] Z=[] X1=[] Y1=[] Z1=[] for residue in self.residues: if (residue in self.ultimate_distance.keys()) and (self.ultimate_distance[residue]<=threshold): if self.ultimate_distance[residue]<=threshold/2: X1.append(acc_back[residue]) Z1.append(self.ultimate_diel[residue]) else: X.append(acc_back[residue]) Z.append(self.ultimate_diel[residue]) interactions=[] for titgroup in self.titgroups: if (titgroup[:6] in self.ultimate_distance.keys()): if (titgroup[-3:]=='HIS') or (titgroup[-3:]=='ASP') or (titgroup[-3:]=='GLU'): diel=self.ultimate_diel[residue] interactions.append(self.dict_CS[diel][residue][titgroup]) interactions.sort() for titgroup in self.titgroups: if interactions[0]==self.dict_CS[diel][residue][titgroup]: if self.ultimate_distance[residue]<=threshold/2: Y1.append(acc_side[titgroup[:6]]) else: Y.append(acc_side[titgroup[:6]]) break clf() import matplotlib.axes3d as p3 fig=figure(num=1,dpi=400,figsize=(10,5),frameon=False) ax = p3.Axes3D(fig) ax.scatter3D(array(X),array(Y),array(Z),color='b') ax.scatter3D(array(X1),array(Y1),array(Z1),color='r') ax.set_xlabel('back access residue') ax.set_ylabel('side chain access titgroup') ax.set_zlabel('effective diel') file_name=dir_name+'3Daccessibility_vs_diel.png' savefig(file_name)
def display_heat_diamond(state_list, sample_size): import pylab as p import matplotlib.axes3d as p3 #--- Get rid of the first bit if we don't need it, and turn -1 into 0 list = prep_list(state_list, False) #--- First build the diamond diamond1 = [] diamond2 = [] size = len(list[0]) + 1 diamond1.append(float(size) / 2.0) diamond2.append(float(size) / 2.0) for i in range(1, (size)): width = minimum(i, (size - i)) diamond1.append((float(size) / float(2)) + float(width)) diamond2.append((float(size) / float(2)) - float(width)) diamond1.append(float(size) / float(2)) diamond2.append(float(size) / float(2)) #plot(diamond1, 'b') #plot(diamond2, 'b') #--- Now build the heat map #-- Init the grid grid = [] for i in range(size): grid.append([]) for j in range(size): grid[i].append(0) #-- Fill in the grid for state in list: x = getX(state) y = int(getY(state)) #print "(" + str(getX(state)) + "," + str(getY(state)) + ")" #print str(x) + "," + str(y) grid[x][y] += float(1) / float(len(list)) #for row in range(len(grid)): # for col in range(len(grid[0])): # print grid[row][col], # print "\n", data = [] path_x = [] path_y = [] path_z = [] for row in range(len(grid)): for col in range(len(grid[0])): data.append((col, row, grid[row][col])) x_step = 1 / float(len(grid[0])) y_step = 1 / float(len(grid)) X, Y = meshgrid(arange(0, 1.0, x_step), arange(0, 1.0, y_step)) Z = zeros((len(Y), len(X)), 'Float32') for d in data: x, y, z = d ix = int(x) iy = int(y) Z[iy, ix] = z fig = p.figure() ax = p3.Axes3D(fig) ax.plot_wireframe(X, Y, Z) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('probability') p.show()
phi = linspace(0, 2 * pi, 50) theta = linspace(-pi / 2, pi / 2, 200) ax = [] ay = [] az = [] R = 1.0 for t in theta: polar = float(t) for k in phi: azim = float(k) sph = special.sph_harm(0, 5, azim, polar) # Y(m,l,phi,theta) modulation = 0.2 * abs(sph) r = R * (1 + modulation) x = r * cos(polar) * cos(azim) y = r * cos(polar) * sin(azim) z = r * sin(polar) # print z # print x,y,z ax.append(x) ay.append(y) az.append(z) fig = p.figure() f = p3.Axes3D(fig) f.set_xlabel('X') f.set_ylabel('Y') f.set_zlabel('Z') f.scatter3D(ax, ay, az) p.show()
#!/usr/bin/env python from numpy import arange, cos, linspace, ones, pi, sin, outer import pylab import matplotlib.axes3d as axes3d fig = pylab.gcf() ax3d = axes3d.Axes3D(fig) plt = fig.axes.append(ax3d) delta = pi / 199.0 u = arange(0, 2 * pi + (delta * 2), delta * 2) v = arange(0, pi + delta, delta) x = outer(cos(u), sin(v)) y = outer(sin(u), sin(v)) z = outer(ones(u.shape), cos(v)) #ax3d.plot_wireframe(x,y,z) surf = ax3d.plot_surface(x, y, z) surf.set_array(linspace(0, 1.0, len(v))) ax3d.set_xlabel('X') ax3d.set_ylabel('Y') ax3d.set_zlabel('Z') pylab.show() #pylab.savefig('simple3d.svg')