Sunday, 15 March 2015

python - plotting the projection of 3D plot in three planes using contours -



python - plotting the projection of 3D plot in three planes using contours -

i have 3 columns catalogue of data , create 3d plot of them plus projection of each axis projected contour in the plane of other 2 axises. far create 3d plot using matplotlib still doesn't show properties of data.

from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot plt numpy import * data=loadtxt('test.cat') x=data[:,0] y=data[:,1] z=data[:,2] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x, y, z, c='r', marker='.') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show()

how plot projection of info in each plane colorbar well?

here's hoping i'm not shooting mosquito [very ugly] cannon, made binning_array class school project , think might able help you:

import numpy np import matplotlib.pyplot plt import binning_array ba mpl_toolkits.mplot3d import axes3d info = np.loadtxt('test.cat') x = data[:,0] y = data[:,1] z = data[:,2] n_points = data.shape[0] x_min = np.round(np.min(data[:,0])-0.5) x_max = np.round(np.max(data[:,0])+0.5) y_min = np.round(np.min(data[:,1])-0.5) y_max = np.round(np.max(data[:,1])+0.5) z_min = np.round(np.min(data[:,2])-0.5) z_max = np.round(np.max(data[:,2])+0.5) n_min_bins = 25 step = min([(x_max-x_min)/n_min_bins, (y_max-y_min)/n_min_bins, (z_max-z_min)/n_min_bins]) # using 3 binners binnerxy = ba.binning_array([[x_min, x_max, step], [y_min, y_max, step]]) binneryz = ba.binning_array([[y_min, y_max, step], [z_min, z_max, step]]) binnerxz = ba.binning_array([[x_min, x_max, step], [z_min, z_max, step]]) point in data: binnerxy.add_value([point[0], point[1]]) binnerxz.add_value([point[0], point[2]]) binneryz.add_value([point[1], point[2]]) fig = plt.figure() ax = [fig.add_subplot(221, projection='3d'), fig.add_subplot(222), fig.add_subplot(223), fig.add_subplot(224)] # plot 2d projections on 3d graph vmin = np.min([binnerxz.bin_min(), binneryz.bin_min(), binnerxy.bin_min()]) vmax = np.max([binnerxz.bin_max(), binneryz.bin_max(), binnerxy.bin_max()]) levels = np.linspace(vmin,vmax,20) xs_c = np.arange(*binnerxz.limits[0]) zs_c = np.arange(*binnerxz.limits[1]) zs_c, xs_c = np.meshgrid(zs_c,xs_c) ax[0].contourf(x=xs_c, y=binnerxz.bins, z=zs_c, zdir='y', offset=y_max, vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm, levels=levels, alpha=0.5) xs_c = np.arange(*binnerxy.limits[0]) ys_c = np.arange(*binnerxy.limits[1]) ys_c, xs_c = np.meshgrid(ys_c,xs_c) ax[0].contourf(x=xs_c, y=ys_c, z=binnerxy.bins, zdir='z', offset=z_min, vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm, levels=levels, alpha=0.5) ys_c = np.arange(*binneryz.limits[0]) zs_c = np.arange(*binneryz.limits[1]) zs_c, ys_c = np.meshgrid(zs_c, ys_c) ax[0].contourf(x=binneryz.bins, y=ys_c, z=zs_c, zdir='x', offset=x_min, vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm, levels=levels, alpha=0.5) # plot scatter of info ax[0].scatter(x, y, z, c='g', marker='.', alpha=0.2) ax[0].set_xlabel(r"$x$") ax[0].set_ylabel(r"$y$") ax[0].set_zlabel(r"$z$") max_range = max([x_max-x_min, y_max-y_min, z_max-z_min]) / 2. pos = [(x_max+x_min)/2., (y_max+y_min)/2., (z_max+z_min)/2.] ax[0].set_xlim(pos[0] - max_range, pos[0] + max_range) ax[0].set_ylim(pos[1] - max_range, pos[1] + max_range) ax[0].set_zlim(pos[2] - max_range, pos[2] + max_range) # plot 2d histograms binnerxz.plot_2d_slice(fig=fig, ax=ax[1], xlabel=r"$x$", ylabel=r'$z$') binnerxy.plot_2d_slice(fig=fig, ax=ax[2], xlabel=r"$x$", ylabel=r'$y$') binneryz.plot_2d_slice(fig=fig, ax=ax[3], xlabel=r"$y$", ylabel=r'$z$') plt.show()

you can utilize 1 binner, notice artifacts planes intersect:

# ... # using 3 binners # ... # using 1 binner (adds little error! see comments!) binner = ba.binning_array([[x_min, x_max, step], [y_min, y_max, step], [z_min, z_max, step]]) point in data: binner.add_value([point[0], point[1], z_min]) binner.add_value([point[0], y_max-step, point[2]]) binner.add_value([x_min, point[1], point[2]]) fig = plt.figure() ax = [fig.add_subplot(221, projection='3d'), fig.add_subplot(222), fig.add_subplot(223), fig.add_subplot(224)] ax[0].scatter(x, y, z, c='g', marker='.', alpha=0.2) binner.plot_slices(others={0:x_min, 1:y_max, 2:z_min}, fig=fig, ax=ax) plt.show()

the binning_array.py made school project , not exclusively polished, it's plenty want.

import numpy np import matplotlib.pyplot plt mpl_toolkits.mplot3d import axes3d class binning_array: def __init__(self, limits=[[-1.,1.,1.],[-1.,1.,1.]]): """create new binning array. amount of given limits determines dimension of array, although 2 , 3d have been tested. each limit must list of start, stop , step axis represents (x, y or z).""" self.limits = np.array(limits) self._shape = [] in xrange(len(self.limits)): self._shape.append((self.limits[i][1]-self.limits[i][0]) / \ float(self.limits[i][2])) self._shape = tuple(self._shape) self.dimensions = len(self._shape) self.bins = np.zeros(self._shape) self.outside = 0. self._normalized = 1. def __repr__(self): """representation method. <<review>>""" homecoming "binning array! hurray!" def __getitem__(self, index): """direct acess read self.bins (use self[index]) direct acess write given __setitem__ """ homecoming self.bins.__getitem__(index) def position2index(self,position,axis=0): """convert given position index in axis. if outside, returns -1. """ if self.limits[axis][0] <= position < self.limits[axis][1]: homecoming int((position - self.limits[axis][0]) / self.limits[axis][2]) else: homecoming -1 def index2position(self, index, axis=0): """convert given index position in axis. if outisde, returns -1. """ if 0 <= index < self._shape[axis]: homecoming self.limits[axis][0] + self.limits[axis][2] * index else: homecoming -1 def add_value(self, position, value=1., verbose=false): """add given value specified position. if verbose returns list axies @ position outside scope of binning_array. not efficient because of (verbose debugging). """ indexs = [] outside = false if verbose: outs = [] in xrange(self.dimensions): # using self.dimensions serves filter # if position has non valid shape index = self.position2index(position[i],i) if index == -1: if verbose: outside = true outs.append(i) else: self.outside += value / self._normalized homecoming none # nothing, not verbose else: indexs.append(index) if outside: # way here if verbose true... self.outside += value / self._normalized homecoming outs # can homecoming outs... else: self.bins[tuple(indexs)] += value / self._normalized if verbose: homecoming outs def get_value(self, position, verbose=false): """return value @ specified position. if verbose alse returns list axies @ position outside scope of binning_array. """ indexs = [] outside = false if verbose: outs = [] in xrange(self.dimensions): index = self.position2index(position[i],i) if index == -1: if verbose: outside = true outs.append[i] else: homecoming self.outside else: indexs.append(index) if outside: # way here if verbose true homecoming self.outside, outs # can homecoming outs... else: if verbose: homecoming self.bins[tuple(indexs)], outs else: homecoming self.bins[tuple(indexs)] def normalize(self, total=none): """divide entire array sum of values (and outside). value added after normalized same factor. """ if total none: total = self.n_counts() self.bins /= total self.outside /= total self.normalize *= total def n_counts(self): """return number of counts.""" homecoming np.sum(self.bins) + self.outside def bin_max(self): """return value of largest bin.""" homecoming np.max(self.bins) def bin_min(self): """return value of largest bin.""" homecoming np.min(self.bins) def plot_2d_slice(self, cuts=[0,1], others={}, fig=none, ax=none, show=true, **kwargs): """plot 2d slice.""" x = min(cuts) y = max(cuts) xs = np.arange(self.limits[x][0], self.limits[x][1] + self.limits[x][2], self.limits[x][2]) ys = np.arange(self.limits[y][0], self.limits[y][1] + self.limits[y][2], self.limits[y][2]) index = [] title = '' in xrange(self.dimensions): if in cuts: appendix = slice(self._shape[i]+1) else: appendix = others.get(i,(self.limits[i][0]+ self.limits[i][1]) / 2.) title += '%d:%.4e\t' % (i,appendix) appendix = self.position2index(appendix,i) index.append(appendix) index = tuple(index) if fig none: fig, ax = plt.subplots(1,1) ys,xs = np.meshgrid(ys, xs) graph = ax.pcolormesh (xs, ys, self.bins[index], cmap=plt.cm.coolwarm) fig.colorbar(graph, ax=ax) ax.axis('equal') ax.set_xlim(self.limits[x][0], self.limits[x][1]) ax.set_ylim(self.limits[y][0], self.limits[y][1]) if 'xticks' in kwargs: ax.set_xticks(kwargs['xticks']) if 'yticks' in kwargs.keys(): ax.set_yticks(kwargs['yticks']) if 'xlabel' in kwargs: ax.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: ax.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs: ax.set_xlim(*kwargs['xlim']) if 'ylim' in kwargs: ax.set_ylim(*kwargs['ylim']) if show: fig.tight_layout() fig.show() def plot_slices(self, others={}, fig=none, ax=none, show=true, projections=true): index = [] pos = [] title = '' in xrange(self.dimensions): temp = others.get(i,(self.limits[i][0]+self.limits[i][1])/2.) title += '%d:%.4e\t' % (i,temp) pos.append(temp) index.append(self.position2index(temp,i)) if self.dimensions == 3: if fig none: fig = plt.figure() if projections: ax = [fig.add_subplot(221, projection='3d'), fig.add_subplot(222), fig.add_subplot(223), fig.add_subplot(224)] else: ax = fig.add_subplot(111, projection='3d') if projections: xs = np.arange(self.limits[0][0], self.limits[0][1] + self.limits[0][2], self.limits[0][2]) ys = np.arange(self.limits[1][0], self.limits[1][1] + self.limits[1][2], self.limits[1][2]) zs = np.arange(self.limits[2][0], self.limits[2][1] + self.limits[2][2], self.limits[2][2]) xs_c = np.arange(*self.limits[0]) ys_c = np.arange(*self.limits[1]) zs_c = np.arange(*self.limits[2]) vmin = np.min(self.bins) vmax = np.max(self.bins) levels = np.linspace(vmin,vmax,20) #graph 0 (3d) ax[0].set_xlabel(r"$x$") ax[0].set_ylabel(r"$y$") ax[0].set_zlabel(r"$z$") #ax[0].axis('equal') #not supported in 3d: #http://stackoverflow.com/questions/13685386/\ #matplotlib-equal-unit-length-with-equal-aspect-ratio-z-axis-is-not-equal-to max_range = max([xs[-1]-xs[0],ys[-1]-ys[0],zs[-1]-zs[0]]) / 2. # x_mean = (xs[-1] + xs[0])/2. # y_mean = (ys[-1] + ys[0])/2. # z_mean = (zs[-1] +zs[0])/2. ax[0].set_xlim(pos[0] - max_range, pos[0] + max_range) ax[0].set_ylim(pos[1] - max_range, pos[1] + max_range) ax[0].set_zlim(pos[2] - max_range, pos[2] + max_range) # understand holes in contour plot: #http://stackoverflow.com/questions/18897950/\ #matplotlib-pyplot-contourf-function-introduces-holes-or-gaps-when-plotting-regul # graph 1 (2d) zs, xs = np.meshgrid(zs,xs) zs_c, xs_c = np.meshgrid(zs_c,xs_c) ax[1].pcolormesh(xs, zs, self.bins[:,index[1],:], vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm) ax[0].contourf(x=xs_c, y=self.bins[:,index[1],:], z=zs_c, zdir='y', offset=pos[1], vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm, levels=levels, alpha=0.5) ax[1].set_xlabel(r"$x$") ax[1].set_ylabel(r"$z$") ax[1].set_xlim(xs[0],xs[-1]) ax[1].set_ylim(zs[0],zs[-1]) ax[1].axis('equal') # graph 2 (2d) ys, xs = np.meshgrid(ys,xs) ys_c, xs_c = np.meshgrid(ys_c,xs_c) ax[2].pcolormesh(xs, ys, self.bins[:,:,index[2]], vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm) ax[0].contourf(x=xs_c, y=ys_c, z=self.bins[:,:,index[2]], zdir='z', offset=pos[2], vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm, levels=levels, alpha=0.5) ax[2].set_xlabel(r"$x$") ax[2].set_ylabel(r"$y$") ax[2].set_xlim(xs[0],xs[-1]) ax[2].set_ylim(ys[0],ys[-1]) ax[2].axis('equal') # graph 3 (2d) zs, ys = np.meshgrid(zs, ys) zs_c, ys_c = np.meshgrid(zs_c, ys_c) ax[3].pcolormesh(ys, zs, self.bins[index[0],:,:], vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm) ax[0].contourf(x=self.bins[index[0],:,:], y=ys_c, z=zs_c, zdir='x', offset=pos[0], vmin=vmin, vmax=vmax, cmap=plt.cm.coolwarm, levels=levels, alpha=0.5) ax[3].set_xlabel(r"$y$") ax[3].set_ylabel(r"$z$") ax[3].set_xlim(ys[0],ys[-1]) ax[3].set_ylim(zs[0],zs[-1]) ax[3].axis('equal') else: # update draw given slice, utilize plot eaxh axes above! ax.plot(self.xs,self.ys,self.zs) ax.set_zlabel(r"$z$") ax.set_xlabel(r"$x$") ax.set_ylabel(r"$y$") ax.axis('equal') else: if fig none: fig, ax = plt.subplots(1) xs = np.arange(self.limits[0][0], self.limits[0][1] + self.limits[0][2], self.limits[0][2]) ys = np.arange(self.limits[1][0], self.limits[1][1] + self.limits[1][2], self.limits[1][2],) ys, xs = np.meshgrid(ys, xs) graph = ax.pcolormesh(xs, ys, self.bins, cmap=plt.cm.coolwarm) fig.colorbar(graph) ax.set_xlim(self.limits[0][0], self.limits[0][1]) ax.set_ylim(self.limits[1][0], self.limits[1][1]) ax.set_title('energy distribution') ax.set_xlabel(r"$x$") ax.set_ylabel(r"$y$") ax.axis('equal') if show: fig.tight_layout() fig.show() homecoming fig, ax

if on code wrong or bugged please , edit above (the school project graded, won't doing homework). also, if less clear please add together comments or explanations needed.

python matplotlib contour

No comments:

Post a Comment