def plot_maps(plot_params, anat_fn, anat_slice_def, fig_dir, orientation=['axial','sagittal'], crop_extension=None, plot_anat=True, plot_fontsize=25, fig_dpi=75): ldata = [] for p in plot_params: c = xndarray.load(p['fn']).sub_cuboid(**p['slice_def']) c.set_orientation(orientation) ldata.append(c.data) c_anat = xndarray.load(anat_fn).sub_cuboid(**anat_slice_def) c_anat.set_orientation(orientation) resolution = c_anat.meta_data[1]['pixdim'][1:4] slice_resolution = resolution[MRI4Daxes.index(orientation[0])], \ resolution[MRI4Daxes.index(orientation[1])] all_data = np.array(ldata) if 'prl' in plot_params[0]['fn']: norm = normalize(all_data.min(), all_data.max()*1.05) print 'norm:', (all_data.min(), all_data.max()) else: norm = normalize(all_data.min(), all_data.max()) print 'norm:', (all_data.min(), all_data.max()) for data, plot_param in zip(all_data, plot_params): fn = plot_param['fn'] plt.figure() print 'fn:', fn print '->', (data.min(), data.max()) if plot_anat: anat_data = c_anat.data else: anat_data = None plot_func_slice(data, anatomy=anat_data, parcellation=plot_param.get('mask'), func_cmap=cmap, parcels_line_width=1., func_norm=norm, resolution=slice_resolution, crop_extension=crop_extension) set_ticks_fontsize(plot_fontsize) fig_fn = op.join(fig_dir, '%s.png' %op.splitext(op.basename(fn))[0]) output_fig_fn = plot_param.get('output_fig_fn', fig_fn) print 'Save to: %s' %output_fig_fn plt.savefig(output_fig_fn, dpi=fig_dpi) autocrop(output_fig_fn) return norm
def plot_representation(Theta, breaks, atoms_order, grid): J, S = Theta.shape pl.subplot2grid(grid, (grid[0] - 6, 0), rowspan=2, colspan=2) # Color boundaries and cmap vmax = 1.0 vmin = -1.0 norm = mlcol.normalize(vmax=vmax, vmin=vmin) cmap = mlcm.RdBu_r im_ref = pl.imshow(Theta[atoms_order], aspect='auto', interpolation='none', norm=norm, cmap=cmap) plot_breaks(np.arange(1, S, 1), orientation='v', ls='--') plot_breaks(np.arange(1, J, 1), orientation='h') pl.xticks(range(S), ['S%d' % t for t in range(1, S + 1)]) pl.yticks(range(J), ['A#%d' % t for t in range(1, J + 1)], weight='bold') ax = pl.gca() for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(FONT_SIZE) tick.tick1On = False tick.tick2On = False for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(FONT_SIZE) tick.tick1On = False tick.tick2On = False
def __init__( self, data, ax, prefs, *args, **kw ): PlotBase.__init__( self, data, ax, prefs, *args, **kw ) if type( data ) == types.DictType: self.gdata = GraphData( data ) elif type( data ) == types.InstanceType and data.__class__ == GraphData: self.gdata = data if self.prefs.has_key( 'span' ): self.width = self.prefs['span'] else: self.width = 1.0 if self.gdata.key_type == "time": nKeys = self.gdata.getNumberOfKeys() self.width = ( max( self.gdata.all_keys ) - min( self.gdata.all_keys ) ) / nKeys # Setup the colormapper to get the right colors self.cmap = LinearSegmentedColormap( 'quality_colormap', cdict, 256 ) #self.cmap = cm.RdYlGn self.norms = normalize( 0, 100 ) mapper = cm.ScalarMappable( cmap = self.cmap, norm = self.norms ) mapper = cm.ScalarMappable( cmap = cm.RdYlGn, norm = self.norms ) def get_alpha( *args, **kw ): return 1.0 mapper.get_alpha = get_alpha self.mapper = mapper
def plot_representation(Theta, breaks, atoms_order): fig = pl.figure() pl.suptitle(r'Representation coefficients ($\Theta$)', weight='bold', size=8) J, S = Theta.shape # Color boundaries and cmap tmin = Theta.min() vmin = 0.0 if tmin >= 0.0 else -np.ceil(np.abs(tmin)) vmax = np.ceil(Theta.max()) norm = mlcol.normalize(vmax=vmax, vmin=vmin) if vmin == 0.0: cmap = mlcm.Reds else: cmap = mlcm.RdBu_r im_ref = pl.imshow(Theta[atoms_order], aspect='auto', interpolation='none', norm=norm, cmap=cmap) plot_breaks(np.arange(1, S, 1), orientation='v', ls='--') plot_breaks(np.arange(1, J, 1), orientation='h') pl.xticks(range(S), ['S%d' % t for t in range(1, S + 1)], size=5) #pl.xticks(range(19, S, 20), [str(x+1) for x in range(19, S, 20)], size=10) pl.yticks(range(J), ['A%d' % (t + 1) for t in atoms_order], size=10) cb = pl.colorbar(extend='both', orientation='horizontal')
def __init__(self, data, ax, prefs, *args, **kw): PlotBase.__init__(self, data, ax, prefs, *args, **kw) if type(data) == types.DictType: self.gdata = GraphData(data) elif type(data) == types.InstanceType and data.__class__ == GraphData: self.gdata = data if self.prefs.has_key('span'): self.width = self.prefs['span'] else: self.width = 1.0 if self.gdata.key_type == "time": nKeys = self.gdata.getNumberOfKeys() self.width = (max(self.gdata.all_keys) - min(self.gdata.all_keys)) / nKeys # Setup the colormapper to get the right colors self.cmap = LinearSegmentedColormap('quality_colormap', cdict, 256) #self.cmap = cm.RdYlGn self.norms = normalize(0, 100) mapper = cm.ScalarMappable(cmap=self.cmap, norm=self.norms) mapper = cm.ScalarMappable(cmap=cm.RdYlGn, norm=self.norms) def get_alpha(*args, **kw): return 1.0 mapper.get_alpha = get_alpha self.mapper = mapper
def colorify(data, vmin=None, vmax=None, cmap=plt.cm.Spectral): """ Associate a color map to a quantity vector Parameters ---------- data: sequence values to index vmin: float, optional minimal value to index vmax: float, optional maximal value to index cmap: colormap instance colormap to use Returns ------- colors: sequence color sequence corresponding to data scalarMap: colormap generated map """ import matplotlib.colors as colors _vmin = vmin or min(data) _vmax = vmax or max(data) cNorm = colors.normalize(vmin=_vmin, vmax=_vmax) scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=cmap) colors = map(scalarMap.to_rgba, data) return colors, scalarMap
def plotHeat(): # open the DataFile.csv with open(sys.argv[2]) as dat: # read the first line and pull out the years years = map(convertStr, dat.readline().strip(',\n').split(',')[1:]) # prepare the datatype # 1 int for the node, and then as many floats as years dattype = [('nodes', np.int64)] + [('', np.float64)] * len(years) # load the file (minus the first line) hdata = np.loadtxt(dat, delimiter=',', dtype=dattype) # map the resulting structure hdata = hdata.view( np.dtype([('nodes', np.int64), ('heat', np.float64, len(years))])) heat = hdata['heat'] nodes = hdata['nodes'] # define grid. xi = np.linspace(-max, max, 2 * max) yi = np.linspace(-max, max, 2 * max) # choose a year to plot for yr in years: plt.clf() plotGeom() # figure out which year yrToPlt = np.float64(yr) index = np.nonzero(years == yrToPlt)[0][0] # define the z data, heat, in the order of the xyznodes z = np.zeros(len(xyznodes)) i = 0 for num in xyznodes: j = np.nonzero(nodes == num)[0][0] #z[i]=heat[j][np.nonzero(years==year)[0][0]] z[i] = heat[j][index] i = i + 1 # grid the data. zi = griddata(x, y, z, xi, yi) scale = colors.normalize(1, heat.max()) # contour the gridded data, plotting dots at the nonuniform data points. CS = plt.contour(xi, yi, zi, 10, linewidths=0.5, colors='k') CS = plt.contourf(xi, yi, zi, 10, cmap=plt.cm.jet, norm=scale) # draw colorbar plt.colorbar() plt.xlim(-1, xlimit) plt.ylim(-ylimit, ylimit) plt.title('Heat during year %d' % yrToPlt) if yrToPlt < 10: plt.savefig('heat/heat0000%d.png' % yrToPlt) elif yrToPlt < 100: plt.savefig('heat/heat000%d.png' % yrToPlt) elif yrToPlt < 1000: plt.savefig('heat/heat00%d.png' % yrToPlt) elif yrToPlt < 10000: plt.savefig('heat/heat0%d.png' % yrToPlt) elif yrToPlt < 10000: plt.savefig('heat/heat%d.png' % yrToPlt) elif yrToPlt >= 100000: sys.exit("Too many years, please shorten input files.") # build a movie retcode = sp.call(["convert", "-set delay 24 /heat/heat*.png bob.gif"])
def __init__(self, cmapName="hsv", indexMin=0, indexMax=1): """ cmapName: color map name indexMin, indexMax: mininal and maximal value of index used used for normalization """ #self.cmap = cm.cmap_d[cmapName] # color map instance self.cmap = cm.get_cmap(cmapName) # color map instance self.norm = colors.normalize(indexMin, indexMax) # normalize instance
def plot_coverage_feature(self, nb_layer_two_neurons=3, nb_stddev=1.0, alpha_ellipses=0.5, facecolor_layerone='b', ax=None, lim_factor=1.1, top_neurons=None, precision=100): ''' Plot the coverage of the network Do a subplot, show the lower layer coverage, and for the random upper layer show some "receptive fields" ''' # Select layer two neurons to be plotted randomly if top_neurons is None: top_neurons = np.random.randint(self.M_layer_two, size=nb_layer_two_neurons) # Get the activities of those layer two neurons activities_layertwo = np.zeros((nb_layer_two_neurons, precision, precision)) for i, layer_two_neuron in enumerate(top_neurons): activities_layertwo[i], feature_space1, feature_space2 = self.get_neuron_activity(layer_two_neuron, precision=precision, return_axes_vect=True) # Construct the plot f = plt.figure() axes_top = ImageGrid(f, 211, nrows_ncols = (1, nb_layer_two_neurons), direction="row", axes_pad = 0.2, add_all=True, label_mode = "L", share_all = True, cbar_location="right", cbar_mode="single", cbar_size="5%", cbar_pad=0.2, ) norm = pltcol.normalize(vmax=activities_layertwo.max(), vmin=activities_layertwo.min()) selected_ticks = np.array(np.linspace(0, feature_space1.size-1, 5), dtype=int) for ax_top, activity_neuron in zip(axes_top, activities_layertwo): im = ax_top.imshow(activity_neuron.T, norm=norm, origin='lower left') ax_top.set_xticks(selected_ticks) ax_top.set_xticklabels((r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$'), fontsize=16) ax_top.set_yticks(selected_ticks) ax_top.set_yticklabels((r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$'), fontsize=16) # ax_top.set_xlabel('Orientation') # ax_top.set_ylabel('Colour') ax_top.cax.colorbar(im) ax_top.cax.toggle_label(True) # Bottom part now ax_bottom = f.add_subplot(2, 3, 5) plt.subplots_adjust(hspace=0.5) self.layer_one_network.plot_coverage_feature_space(nb_stddev=2, facecolor=facecolor_layerone, alpha_ellipses=alpha_ellipses, lim_factor=lim_factor, ax=ax_bottom, specific_neurons=np.arange(0, self.M_layer_one, 2)) return axes_top, ax_bottom
def pproc(filename, inArray, dir, max_value, padding, show_plot): array = dirArray(inArray[0], dir) #with open('1.dat', 'w') as f: # for item in xArray: # f.write(str(item)) mat = FilterMap(max_value, padding) mat.filter(array) #plt.imshow(mat.result) maxV = max(map(max, mat.result)) minV = min(map(min, mat.result)) if (maxV**2 > minV**2): mv = np.sqrt(maxV**2) else: mv = np.sqrt(minV**2) print "max value of field: ", mv print "half of max value of field: ", mv/2 # ['Spectral', 'summer', 'RdBu', 'Set1', 'Set2', 'Set3', 'brg_r', 'Dark2', # 'hot', 'PuOr_r', 'afmhot_r', 'terrain_r', 'PuBuGn_r', 'RdPu', 'gist_ncar_r', # 'gist_yarg_r', 'Dark2_r', 'YlGnBu', 'RdYlBu', 'hot_r', 'gist_rainbow_r', # 'gist_stern', 'gnuplot_r', 'cool_r', 'cool', 'gray', 'copper_r', 'Greens_r', # 'GnBu', 'gist_ncar', 'spring_r', 'gist_rainbow', 'RdYlBu_r', 'gist_heat_r', # 'OrRd_r', 'bone', 'gist_stern_r', 'RdYlGn', 'Pastel2_r', 'spring', 'terrain', # 'YlOrRd_r', 'Set2_r', 'winter_r', 'PuBu', 'RdGy_r', 'spectral', 'flag_r', # 'jet_r', 'RdPu_r', 'Purples_r', 'gist_yarg', 'BuGn', 'Paired_r', 'hsv_r', 'bwr', # 'YlOrRd', 'Greens', 'PRGn', 'gist_heat', 'spectral_r', 'Paired', 'hsv', 'Oranges_r', # 'prism_r', 'Pastel2', 'Pastel1_r', 'Pastel1', 'gray_r', 'PuRd_r', 'Spectral_r', # 'gnuplot2_r', 'BuPu', 'YlGnBu_r', 'copper', 'gist_earth_r', 'Set3_r', 'OrRd', # 'PuBu_r', 'ocean_r', 'brg', 'gnuplot2', 'jet', 'bone_r', 'gist_earth', 'Oranges', # 'RdYlGn_r', 'PiYG', 'YlGn', 'binary_r', 'gist_gray_r', 'Accent', 'BuPu_r', 'gist_gray', # 'flag', 'seismic_r', 'RdBu_r', 'BrBG', 'Reds', 'BuGn_r', 'summer_r', 'GnBu_r', 'BrBG_r', # 'Reds_r', 'RdGy', 'PuRd', 'Accent_r', 'Blues', 'Greys', 'autumn', 'PRGn_r', 'Greys_r', # 'pink', 'binary', 'winter', 'gnuplot', 'pink_r', 'prism', 'YlOrBr', 'rainbow_r', 'rainbow', # 'PiYG_r', 'YlGn_r', 'Blues_r', 'YlOrBr_r', 'seismic', 'Purples', 'bwr_r', 'autumn_r', # 'ocean', 'Set1_r', 'PuOr', 'PuBuGn', 'afmhot'] # norm = colors.normalize(-mv, mv) # MUMAX norm = colors.normalize(-1, 1) # norm = colors.LogNorm() # plt.matshow(mat.result, cmap='RdBu', norm=colors.LogNorm() ) plt.matshow(mat.result, norm=norm ) plt.colorbar(shrink=.8) fig = plt.gcf() if (show_plot==True): plt.show() png_name = filename[0:(len(filename)-4)] + "_" "+.png" a = re.split(r'\\', png_name) addr = "" for i in range(len(a)-1): addr += a[i] +"\\" print addr addr += (dir+"_"+a[ len(a)-1 ]) print addr #addr = nn fig.savefig(addr, dpi=100) plt.close()
def colorify(data, vmin=None, vmax=None, cmap=plt.cm.Spectral): """ Associate a color map to a quantity vector """ import matplotlib.colors as colors _vmin = vmin or min(data) _vmax = vmax or max(data) cNorm = colors.normalize(vmin=_vmin, vmax=_vmax) scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=cmap) colors = map(scalarMap.to_rgba, data) return colors, scalarMap
def colorify(data, vmin=None, vmax=None, cmap=plt.cm.Spectral): """ Associate a color map to a quantity vector """ import matplotlib.colors as colors _vmin = vmin or min(data) _vmax = vmax or max(data) cNorm = colors.normalize(vmin=_vmin, vmax=_vmax) scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=cmap) colors = map(scalarMap.to_rgba, data) return colors, scalarMap
def make_mpl_image_properties(func_man): """ Create a dictionary of matplotlib AxesImage color mapping properties from the corresponding properties in an OverlayInterface """ from matplotlib.colors import normalize props = dict() props['cmap'] = func_man.colormap props['interpolation'] = func_man.interpolation props['alpha'] = func_man.alpha() props['norm'] = normalize(*func_man.norm) return props
def __init__(self, cmapName="hsv", indexMin=0, indexMax=1): """ cmapName: color map name indexMin, indexMax: mininal and maximal value of index used used for normalization """ self.cmap = cm.cmap_d[cmapName] # color map instance self.norm = colors.normalize(indexMin, indexMax) # normalize instance self.set_color(indexMin) # implicit setting of point color
def histogram(self): self.ax.set_title('Histogram of Evidence Based Scheduling [ %d ]' % len(self.H)) self.ax.set_xlabel('Time (h)', fontstyle='italic') self.ax.set_ylabel('Probability (%)', fontstyle='italic') self.ax.set_ylim(0, 110) self.ax.grid(True) self.ax.axvline(self.u, color='#90EE90', linestyle='dashed', lw=2) self.H += self.mc.probes(1000) n, bins, patches = self.ax.hist(self.H, bins=self.count, edgecolor='white', alpha=0.75) nmax = n.max() # najwyższy słupek # zmienna skala osi Y self.ax.set_xticks([round(i, 2) for i in bins[::self.scale]]) # self.ax.set_xticklabels(('a','b')) # tak można dodać label zamiast wartości self.figure.autofmt_xdate() # pochyłe literki # strzałka if self.arrow: pyplot.annotate('simple estimation', xy=(self.u, 90), xytext=(min(bins), 100), arrowprops=dict(facecolor='blue', shrink=0.005)) if self.help == 1: pyplot.annotate('help (h)', xy=(max(bins), 90), xytext=((self.u + max(bins)) / 2, 90), ha='left') elif self.help == 2: pyplot.annotate('\n'.join(self.usage), xy=(max(bins), 90), xytext=((self.u + max(bins)) / 2, 60), ha='left') # normalizacja for p in patches: p.set_height((p.get_height() * 100.0) / nmax) # tęcza fracs = n.astype(float) / nmax norm = colors.normalize(fracs.min(), fracs.max()) for f, p in zip(fracs, patches): color = cm.jet(norm(f)) p.set_facecolor(color)
def _proportional_y(self): ''' Return colorbar data coordinates for the boundaries of a proportional colorbar. ''' y = self.norm(self._boundaries.copy()) if self.extend in ('both', 'min'): y[0] = -0.05 if self.extend in ('both', 'max'): y[-1] = 1.05 yi = y[self._inside] norm = colors.normalize(yi[0], yi[-1]) y[self._inside] = norm(yi) return y
def _draw_features(self, **kwargs): xoffset = kwargs.get('xoffset',0) for feat_numb, feat2draw in enumerate(self.features): if feat2draw.color_by_cm: if feat2draw.use_score_for_color: feat2draw.cm_value = feat2draw.score feat2draw.fc = self.cm(feat2draw.cm_value) else:# color by feature number if not feat2draw.cm_value: self.norm = colors.normalize(1,len(self.features)+1,) feat2draw.cm_value = feat_numb +1 feat2draw.fc = self.cm(self.norm(feat2draw.cm_value)) feat2draw.draw_feature() feat2draw.draw_feat_name(xoffset = xoffset)
def add_data(self, data): """ Adiciona serie temporal para UFs [(UF,tempo,valor),...] """ vals = array([i[2] for i in data]) norm = normalize(vals.min(), vals.max()) for i, d in enumerate(data): print i pm = self.pmdict[d[0]] #clone placemark to receive new data pm_newtime = pm.cloneNode(1) # Renaming placemark on = pm_newtime.getElementsByTagName('name')[0] nn = self.kmlDoc.createElement('name') nn.appendChild(self.kmlDoc.createTextNode(d[0]+'-'+str(d[1]))) pm_newtime.replaceChild(nn, on) nl = pm_newtime.childNodes #extrude polygon pol = pm_newtime.getElementsByTagName('Polygon')[0] alt = self.kmlDoc.createElement('altitudeMode') alt.appendChild(self.kmlDoc.createTextNode('relativeToGround')) ex = self.kmlDoc.createElement('extrude') ex.appendChild(self.kmlDoc.createTextNode('1')) ts = self.kmlDoc.createElement('tessellate') ts.appendChild(self.kmlDoc.createTextNode('1')) pol.appendChild(alt) pol.appendChild(ex) pol.appendChild(ts) lr = pm_newtime.getElementsByTagName('LinearRing')[0] nlr = self.extrude_polygon(lr, d[2]) ob = pm_newtime.getElementsByTagName('outerBoundaryIs')[0] # ob.replaceChild(nlr, lr) ob.removeChild(lr) ob.appendChild(nlr) #set polygon style col = rgb2hex(cm.Oranges(norm(d[2]))[:3])+'ff' st = pm_newtime.getElementsByTagName('Style')[0] #style nst = self.set_polygon_style(st, col) pm_newtime.removeChild(st) pm_newtime.appendChild(nst) #add timestamp ts = self.kmlDoc.createElement('TimeStamp') w = self.kmlDoc.createElement('when') w.appendChild(self.kmlDoc.createTextNode(str(d[1]))) ts.appendChild(w) pm_newtime.appendChild(ts) self.folder.appendChild(pm_newtime) for pm in self.pmdict.itervalues(): self.folder.removeChild(pm)
def _proportional_y(self): """ Return colorbar data coordinates for the boundaries of a proportional colorbar. """ y = self.norm(self._boundaries.copy()) if self.extend in ("both", "min"): y[0] = -0.05 if self.extend in ("both", "max"): y[-1] = 1.05 yi = y[self._inside] norm = colors.normalize(yi[0], yi[-1]) y[self._inside] = norm(yi) return y
def plot_reconstruction(Y, Yest, J, breaks, title): fig = pl.figure() pl.suptitle('Data reconstruction (%s)' % title, weight='bold', size=8) L, S = Y.shape # Color boundaries and cmap vmin = -2.5 * Y.std() vmax = 2.5 * Y.std() norm = mlcol.normalize(vmax=vmax, vmin=vmin) cmap = mlcm.RdBu_r fit_error = np.sum((Y - Yest)**2.) / (S * L) IMAGES = {'$Y$': Y.T, '$\\hat{Y}$ [$Err=%2.3e$]' % fit_error: Yest.T} for i, k in enumerate(IMAGES): pl.subplot(2, 1, i + 1) im_ref = pl.imshow(IMAGES[k], aspect='auto', interpolation='none', norm=norm, cmap=cmap) ax = pl.gca() plot_breaks(breaks) add_chr_ticks(ax, breaks, L) pl.title(k, size=8) #plot_breaks(np.arange(1, S, 1), orientation='h', ls='--') pl.yticks(range(S), ['S%d' % t for t in range(1, S + 1)]) #pl.yticks(range(19, S, 20), [str(x+1) for x in range(19, S, 20)], size=10) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(6) tick.tick1On = False tick.tick2On = False for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(5) tick.tick1On = False tick.tick2On = False pl.tight_layout(pad=2.0) # Make an axis for the colorbar on the right side pl.subplots_adjust(right=0.85) cax = fig.add_axes([0.9, 0.1, 0.03, 0.8]) cb = fig.colorbar(im_ref, cax=cax, extend='both') for t in cb.ax.get_yticklabels(): t.set_fontsize(6)
def plot_mod(x, z, yvals, ylabel, ax, ind=0, cmap=pl.cm.rainbow, printlabel=True): """ Plot column-density-derived values yvals as a function of the x values (NHI, nH or Z), showing variation of quantity z by different coloured curves. ind is the index of the value used, which isn't varied. """ # Want index order to be indtype, x, z. By default it's NHI, nH, # Z. Otherwise it has to change... if (x, z) == ('NHI', 'Z'): yvals = np.swapaxes(yvals, 0, 1) elif (x, z) == ('Z', 'NHI'): yvals = np.swapaxes(yvals, 0, 1) yvals = np.swapaxes(yvals, 1, 2) elif (x, z) == ('nH', 'NHI'): yvals = np.swapaxes(yvals, 0, 2) elif (x, z) == ('NHI', 'nH'): yvals = np.swapaxes(yvals, 0, 2) yvals = np.swapaxes(yvals, 1, 2) elif (x, z) == ('Z', 'nH'): yvals = np.swapaxes(yvals, 1, 2) norm = colors.normalize(M[z].min(), M[z].max()) label_indices = set((0, len(M[z]) // 2, len(M[z]) - 1)) for i in range(len(M[z])): # spring, summer, autumn, winter are all good c = cmap(norm(M[z][i])) label = None if i in label_indices: label = labels[z] % M[z][i] #ax.plot(M[x], yvals[ind,:,i], '-', lw=2.5, color='k') ax.plot(M[x], yvals[ind, :, i], '-', lw=1.5, color=c, label=label) val, = list(set(['nH', 'NHI', 'Z']).difference([x, z])) if printlabel: ax.set_title(labels[val] % M[val][ind], fontsize='medium') ax.title.set_y(1.01) ax.set_xlabel(xlabels[x], fontsize='small') ax.set_ylabel(ylabel) ax.minorticks_on() ax.set_xlim(M[x][0] + 1e-3, M[x][-1] - 1e-3)
def plot_sensor_data(sensor, plot_type="grey", outfile="output.png"): # Create canvas print "Preparing the plot" fig = plt.figure() if (plot_type == "3d"): ax = fig.add_subplot(111, projection='3d') # Calculate 3d plot data: grid xedges = np.arange(0, s.pixel_rows+1) yedges = np.arange(0, s.pixel_columns+1) elements = (len(xedges) - 1) * (len(yedges) - 1) xpos, ypos = np.meshgrid(xedges[:-1]+0.05, yedges[:-1]+0.05) # Calculate starting x, y, z xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(elements) # Areas of the bins, flatten the heights dx = 0.9 * np.ones_like(zpos) dy = dx.copy() dz = np.array(s.data()).flatten() print "Calculating colors..." norm = colors.normalize(dz.min(), dz.max()) col = [] for i in dz: col.append(cm.jet(norm(i))) print "Now rendering image..." ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=col, zsort='average') else: ax = fig.add_subplot(111) dz = np.array(s.data()).flatten() cma = cm.jet if (plot_type == "grey"): cma = cm.Greys cax = ax.imshow(s.data(), interpolation='nearest', cmap=cma) cbar = fig.colorbar(cax, ticks=[dz.min(), (dz.max()+dz.min())/2, dz.max()], orientation='vertical') cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])# horizontal colorbar ax.set_title('Sensor Data') print "Saving image..." plt.savefig(outfile, dpi=500) print "All done!"
def db_to_logs(ano): """ Extrai as decisoes do bancoe as salva em um arquivo no formato do Gource """ #Q = dbdec.execute("SELECT relator,processo,tipo,proc_classe,duracao, UF,data_dec, count(*) FROM decisao WHERE DATE_FORMAT(data_dec,'%Y%')="+"%s"%ano+" GROUP BY relator,tipo,proc_classe") Q = dbdec.execute("SELECT relator,processo,tipo,proc_classe,duracao, UF,data_dec FROM decisao WHERE DATE_FORMAT(data_dec,'%Y%')="+"%s"%ano+" ORDER BY data_dec asc") decs = Q.fetchall() durations = [d[4] for d in decs] cmap = cm.jet norm = normalize(min(durations), max(durations)) #normalizing durations with open('decisoes_%s.log'%ano, 'w') as f: for d in decs: c = rgb2hex(cmap(norm(d[4]))[:3]).strip('#') path = "/%s/%s/%s/%s"%(d[5],d[2],d[3], d[1]) #/State/tipo/proc_classe/processo l = "%s|%s|%s|%s|%s\n"%(int(time.mktime(d[6].timetuple())), d[0], 'A', path, c) f.write(l)
def _draw_features(self, **kwargs): xoffset = kwargs.get('xoffset', 0) for feat_numb, feat2draw in enumerate(self.features): if feat2draw.color_by_cm: if feat2draw.use_score_for_color: feat2draw.cm_value = feat2draw.score feat2draw.fc = self.cm(feat2draw.cm_value) else: # color by feature number if not feat2draw.cm_value: self.norm = colors.normalize( 1, len(self.features) + 1, ) feat2draw.cm_value = feat_numb + 1 feat2draw.fc = self.cm(self.norm(feat2draw.cm_value)) feat2draw.draw_feature() feat2draw.draw_feat_name(xoffset=xoffset)
def histogram(self): self.ax.set_title('Histogram of Evidence Based Scheduling [ %d ]' % len(self.H)) self.ax.set_xlabel('Time (h)',fontstyle='italic') self.ax.set_ylabel('Probability (%)',fontstyle='italic') self.ax.set_ylim(0,110) self.ax.grid(True) self.ax.axvline(self.u, color='#90EE90', linestyle='dashed', lw=2) self.H += self.mc.probes(1000) n, bins, patches = self.ax.hist(self.H, bins=self.count , edgecolor='white', alpha=0.75) nmax=n.max() # najwyższy słupek # zmienna skala osi Y self.ax.set_xticks([ round(i,2) for i in bins[::self.scale] ]) # self.ax.set_xticklabels(('a','b')) # tak można dodać label zamiast wartości self.figure.autofmt_xdate() # pochyłe literki # strzałka if self.arrow: pyplot.annotate('simple estimation', xy=(self.u, 90), xytext=(min(bins), 100), arrowprops=dict(facecolor='blue', shrink=0.005)) if self.help == 1 : pyplot.annotate('help (h)', xy=(max(bins), 90), xytext=((self.u+max(bins))/2, 90), ha='left') elif self.help == 2 : pyplot.annotate('\n'.join(self.usage), xy=(max(bins), 90), xytext=((self.u+max(bins))/2, 60), ha='left') # normalizacja for p in patches: p.set_height((p.get_height() * 100.0 ) / nmax ) # tęcza fracs = n.astype(float)/nmax norm = colors.normalize(fracs.min(), fracs.max()) for f, p in zip(fracs, patches): color = cm.jet(norm(f)) p.set_facecolor(color)
def __init__( self, ax, cmap=None, norm=None, values=None, boundaries=None, orientation="vertical", extend="neither", spacing="uniform", # uniform or proportional ticks=None, format=None, drawedges=False, filled=True, ): self.ax = ax if cmap is None: cmap = cm.get_cmap() if norm is None: norm = colors.normalize() cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm) self.values = values self.boundaries = boundaries self.extend = extend self._inside = self._slice_dict[extend] self.spacing = spacing self.orientation = orientation self.drawedges = drawedges self.filled = filled self.solids = None self.lines = None if iterable(ticks): self.locator = ticker.FixedLocator(ticks, nbins=10) else: self.locator = ticks # Handle default in _ticker() if format is None: self.formatter = ticker.ScalarFormatter() elif is_string_like(format): self.formatter = ticker.FormatStrFormatter(format) else: self.formatter = format # Assume it is a Formatter # The rest is in a method so we can recalculate when clim changes. self.draw_all()
def contour(x, y, z, func=pl.contourf, black=None, **opts): ''' Adds a "black" functionality to default contour function ''' if black != None: clevs = opts.get('levels', None) if clevs != None: min = clevs[0] max = clevs[-1] else: min = sp.ma.minimum(z) max = sp.ma.maximum(z) norm = opts.get('norm', colors.normalize(min, max)) cmap = opts.get('cmap', MyCmap(cm.get_cmap(), black=norm(black))) opts['norm'] = norm opts['cmap'] = cmap cs = func(x, y, z, **opts) return cs
def hist_com_difference_plot(filename,image_output,graph_title=''): distance = [] for line in open(filename): if line[0] == "#" or line[0] == "@": continue line_content = line.split() distance.append(float(line_content[1])) fig = figure() N,bins,patches = hist(distance,range(-30,30)) fracs = N.astype(float)/N.max() norm = colors.normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = cm.jet(norm(thisfrac)) thispatch.set_facecolor(color) xlabel('Z Distance between Protein and Bilayer centers') ylabel('Frequency') title(graph_title) savefig(image_output)
def plot_mod(x, z, yvals, ylabel, ax, ind=0, cmap=pl.cm.rainbow, printlabel=True): """ Plot column-density-derived values yvals as a function of the x values (NHI, nH or Z), showing variation of quantity z by different coloured curves. ind is the index of the value used, which isn't varied. """ # Want index order to be indtype, x, z. By default it's NHI, nH, # Z. Otherwise it has to change... if (x,z) == ('NHI','Z'): yvals = np.swapaxes(yvals, 0, 1) elif (x,z) == ('Z','NHI'): yvals = np.swapaxes(yvals, 0, 1) yvals = np.swapaxes(yvals, 1, 2) elif (x,z) == ('nH','NHI'): yvals = np.swapaxes(yvals, 0, 2) elif (x,z) == ('NHI', 'nH'): yvals = np.swapaxes(yvals, 0, 2) yvals = np.swapaxes(yvals, 1, 2) elif (x,z) == ('Z','nH'): yvals = np.swapaxes(yvals, 1, 2) norm = colors.normalize(M[z].min(), M[z].max()) label_indices = set((0, len(M[z])//2, len(M[z])-1)) for i in range(len(M[z])): # spring, summer, autumn, winter are all good c = cmap(norm(M[z][i])) label = None if i in label_indices: label = labels[z] % M[z][i] #ax.plot(M[x], yvals[ind,:,i], '-', lw=2.5, color='k') ax.plot(M[x], yvals[ind,:,i], '-', lw=1.5, color=c, label=label) val, = list(set(['nH','NHI','Z']).difference([x,z])) if printlabel: ax.set_title(labels[val] % M[val][ind], fontsize='medium') ax.title.set_y(1.01) ax.set_xlabel(xlabels[x], fontsize='small') ax.set_ylabel(ylabel) ax.minorticks_on() ax.set_xlim(M[x][0]+1e-3, M[x][-1]-1e-3)
def __init__( self, ax, cmap=None, norm=None, values=None, boundaries=None, orientation='vertical', extend='neither', spacing='uniform', # uniform or proportional ticks=None, format=None, drawedges=False, filled=True, ): self.ax = ax if cmap is None: cmap = cm.get_cmap() if norm is None: norm = colors.normalize() cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm) self.values = values self.boundaries = boundaries self.extend = extend self._inside = self._slice_dict[extend] self.spacing = spacing self.orientation = orientation self.drawedges = drawedges self.filled = filled self.solids = None self.lines = None if iterable(ticks): self.locator = ticker.FixedLocator(ticks, nbins=10) else: self.locator = ticks # Handle default in _ticker() if format is None: self.formatter = ticker.ScalarFormatter() elif is_string_like(format): self.formatter = ticker.FormatStrFormatter(format) else: self.formatter = format # Assume it is a Formatter # The rest is in a method so we can recalculate when clim changes. self.draw_all()
def hist_tilt_data_plot(filename,image_output,graph_title='',modifier=0.,binwidth=5): tilt = [] for line in open(filename): if line[0] == "#" or line[0] == "@": continue line_content = line.split() if float(line_content[1]) <= 90: tilt.append(float(line_content[1])) else: tilt.append(180 - float(line_content[1])) if modifier != 0: tilt = [modifier-angle for angle in tilt] fig = figure() N,bins,patches = hist(tilt,range(0,90,binwidth)) fracs = N.astype(float)/N.max() norm = colors.normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = cm.jet(norm(thisfrac)) thispatch.set_facecolor(color) xlabel('Tilt angle (degrees)') ylabel('Frequency') title(graph_title) savefig(image_output)
def _plot(map): global axis mpl.rcParams['xtick.labelsize'] = 'medium' mpl.rcParams['ytick.labelsize'] = 'medium' mpl.rcParams['axes.grid'] = False mpl.rcParams['figure.subplot.left'] = 0.06 mpl.rcParams['figure.subplot.right'] = 0.97 mpl.rcParams['figure.subplot.top'] = 0.9 mpl.rcParams['figure.subplot.bottom'] = 0.1 mpl.rcParams['axes.labelsize'] = 'medium' mpl.rcParams['ytick.major.pad'] = 4 mpl.rcParams['xtick.major.pad'] = 4 fig = plt.figure(figsize=(16, 9)) axis = plt.gca() fig.canvas.set_window_title('Contacts Histogram') fig.canvas.mpl_connect('button_press_event', _onpick) bar_heights = np.array(map.values()).astype(float) bar_positions = np.array(map.keys()) bar_rectangles = plt.bar(bar_positions, bar_heights, width=1.0, linewidth=0) plt.xlim(bar_positions.min(), bar_positions.max()) plt.ylim(0, bar_heights.max()+1) plt.title('Contacts Histogram ' + '(cutoff distance = ' + str(distance_cutoff) + ur' \u00c5)' + '\n\n') plt.xlabel('\nResidue Index') plt.ylabel('Count\n') # Set Colors of the bar fractions = bar_heights/bar_heights.max() normalized_colors = colors.normalize(fractions.min(), fractions.max()) count = 0 for rect in bar_rectangles: c = cm.jet(normalized_colors(fractions[count])) rect.set_facecolor(c) count = count + 1 ax_text = plt.axes([0.81, -0.02, 0.13, 0.075], frameon=False) Button(ax_text, 'Click to select and highlight the residue in PyMol...', color=(0.33,0.33,0.33)) fig.show() # This dummy image and drawing it on the canvas is neccessary step to give back CGContextRef to the main window. Otherwise the buttons on main contact map window stops responding. progressbar.ax.set_visible(False) dummy_img = Image.new('RGBA',(x_img_length,y_img_length),(0,0,0,0)) glob_ax.imshow(dummy_img) glob_ax.figure.canvas.draw()
def plot_reconstruction(Y, fit_error, J, breaks, grid): L, S = Y.shape pl.subplot2grid(grid, (grid[0] - 4, 0), rowspan=4, colspan=2) # Color boundaries and cmap vmin = -1.0 vmax = 1.0 norm = mlcol.normalize(vmax=vmax, vmin=vmin) cmap = mlcm.RdBu_r if fit_error: error_tit = r'\||\mathbf{\bar{Y}} - \mathbf{\hat{Y}}\||^2 / (S \cdot L) = %2.3e' % fit_error title = r'$\mathbf{\hat{Y}} \quad\quad [ %s ] $' % error_tit else: title = r'$\mathbf{Y}$' im_ref = pl.imshow(Y.T, aspect='auto', interpolation='none', norm=norm, cmap=cmap) ax = pl.gca() plot_breaks(breaks) add_chr_ticks(ax, breaks, L) pl.title(title, size=FONT_SIZE + 2) pl.yticks(range(S), ['S%d' % t for t in range(1, S + 1)]) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(FONT_SIZE) tick.tick1On = False tick.tick2On = False for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(FONT_SIZE) tick.tick1On = False tick.tick2On = False return ax
def pproc(filename, inArray, dir, max_value, padding, show_plot): array = dirArray(inArray[0], dir) #with open('1.dat', 'w') as f: # for item in xArray: # f.write(str(item)) mat = FilterMap(max_value, padding) mat.filter(array) #plt.imshow(mat.result) maxV = max(map(max, mat.result)) minV = min(map(min, mat.result)) if (maxV**2 > minV**2): mv = np.sqrt(maxV**2) else: mv = np.sqrt(minV**2) print "max value of field: ", mv print "half of max value of field: ", mv/2 norm = colors.normalize(-mv, mv) # MUMAX # norm = colors.normalize(-1, 1) # norm = colors.LogNorm() # plt.matshow(mat.result, cmap='RdBu', norm=colors.LogNorm() ) plt.matshow(mat.result, norm=norm ) plt.colorbar(shrink=.8) fig = plt.gcf() if (show_plot==True): plt.show() png_name = filename[0:(len(filename)-4)] + "_" "+.png" a = re.split(r'\\', png_name) addr = "" for i in range(len(a)-1): addr += a[i] +"\\" print addr addr += (dir+"_"+a[ len(a)-1 ]) print addr #addr = nn fig.savefig(addr, dpi=100) plt.close()
# transform to nx x ny regularly spaced native projection grid # nx and ny chosen to have roughly the same horizontal res as original image. dx = 2.*np.pi*m.rmajor/len(lons) nx = int((m.xmax-m.xmin)/dx)+1; ny = int((m.ymax-m.ymin)/dx)+1 # interpolate to native projection grid. # values outside of projection limb will be masked. topo = m.transform_scalar(topoin,lons,lats,nx,ny,masked=True) ax = fig.add_axes([0.1,0.1,0.7,0.7]) # set missing value in color pallette. palette = plt.cm.jet palette.set_bad(ax.get_axis_bgcolor(), 0.0) # plot image over map with imshow. # (if contourf were used, no interpolation would be necessary # and values outside projection limb would be handled transparently # - see contour_demo.py) im = m.imshow(topo,palette,norm=colors.normalize(clip=False)) m.colorbar() # draw colorbar # draw coastlines and political boundaries. m.drawcoastlines() # draw parallels and meridians (labelling is # not implemented for orthographic). parallels = np.arange(-80.,90,20.) m.drawparallels(parallels) meridians = np.arange(0.,360.,20.) m.drawmeridians(meridians) # draw boundary around map region. m.drawmapboundary() plt.title('Orthographic') print 'plotting Orthographic example ...' print m.proj4string
def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None): """Draws streamlines of a vector flow. *x*, *y* : 1d arrays defines the grid. *u*, *v* : 2d arrays x and y-velocities. Number of rows should match length of y, and the number of columns should match x. *density* : float or 2-tuple Controls the closeness of streamlines. When `density = 1`, the domain is divided into a 30x30 grid---*density* linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use [density_x, density_y]. *linewidth* : numeric or 2d array vary linewidth when given a 2d array with the same shape as velocities. *color* : matplotlib color code, or 2d array Streamline color. When given an array with the same shape as velocities, *color* values are converted to colors using *cmap*. *cmap* : :class:`~matplotlib.colors.Colormap` Colormap used to plot streamlines and arrows. Only necessary when using an array input for *color*. *norm* : :class:`~matplotlib.colors.Normalize` Normalize object used to scale luminance data to 0, 1. If None, stretch (min, max) to (0, 1). Only necessary when *color* is an array. *arrowsize* : float Factor scale arrow size. *arrowstyle* : str Arrow style specification. See :class:`~matplotlib.patches.FancyArrowPatch`. *minlength* : float Minimum length of streamline in axes coordinates. Returns: *stream_container* : StreamplotSet Container object with attributes - lines: `matplotlib.collections.LineCollection` of streamlines - arrows: collection of `matplotlib.patches.FancyArrowPatch` objects representing arrows half-way along stream lines. This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible. """ grid = Grid(x, y) # Handle decreasing x and y by changing sign. The sign is changed # back after the integration routines (not totally happy with # this). x_increasing = grid.x[1] > grid.x[0] if not x_increasing: grid = Grid(-grid.x, grid.y) u = -u y_increasing = grid.y[1] > grid.y[0] if not y_increasing: grid = Grid(grid.x, -grid.y) v = -v mask = StreamMask(density) dmap = DomainMap(grid, mask) # default to data coordinates if transform is None: transform = axes.transData if color is None: color = axes._get_lines.color_cycle.next() if linewidth is None: linewidth = matplotlib.rcParams['lines.linewidth'] line_kw = {} arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize) use_multicolor_lines = isinstance(color, np.ndarray) if use_multicolor_lines: assert color.shape == grid.shape line_colors = [] if np.any(np.isnan(color)): color = np.ma.array(color, mask=np.isnan(color)) else: line_kw['color'] = color arrow_kw['color'] = color if isinstance(linewidth, np.ndarray): assert linewidth.shape == grid.shape line_kw['linewidth'] = [] else: line_kw['linewidth'] = linewidth arrow_kw['linewidth'] = linewidth ## Sanity checks. assert u.shape == grid.shape assert v.shape == grid.shape if np.any(np.isnan(u)): u = np.ma.array(u, mask=np.isnan(u)) if np.any(np.isnan(v)): v = np.ma.array(v, mask=np.isnan(v)) integrate = get_integrator(grid.x, grid.y, u, v, dmap, minlength) trajectories = [] for xm, ym in _gen_starting_points(mask.shape): if mask[ym, xm] == 0: xg, yg = dmap.mask2data(xm, ym) t = integrate(xg, yg) if t is not None: trajectories.append(t) if use_multicolor_lines: if norm is None: norm = mcolors.normalize(color.min(), color.max()) if cmap is None: cmap = cm.get_cmap(matplotlib.rcParams['image.cmap']) else: cmap = cm.get_cmap(cmap) streamlines = [] arrows = [] for t in trajectories: tx = np.array(t[0]) ty = np.array(t[1]) ## undoes the sign change put in place for the handling of ## decreasing x and y arrays. if not x_increasing: tx = -tx if not y_increasing: ty = -ty points = np.transpose([tx, ty]).reshape(-1, 1, 2) streamlines.extend(np.hstack([points[:-1], points[1:]])) # Add arrows half way along each trajectory. s = np.cumsum(np.sqrt(np.diff(tx)**2 + np.diff(ty)**2)) n = np.searchsorted(s, s[-1] / 2.) arrow_tail = (tx[n], ty[n]) arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2])) if isinstance(linewidth, np.ndarray): line_widths = interparray(grid, linewidth, tx, ty)[:-1] line_kw['linewidth'].extend(line_widths) arrow_kw['linewidth'] = line_widths[n] if use_multicolor_lines: color_values = interparray(grid, color, tx, ty)[:-1] line_colors.extend(color_values) arrow_kw['color'] = cmap(norm(color_values[n])) p = patches.FancyArrowPatch(arrow_tail, arrow_head, transform=transform, **arrow_kw) axes.add_patch(p) arrows.append(p) lc = mcollections.LineCollection(streamlines, transform=transform, **line_kw) if use_multicolor_lines: lc.set_array(np.asarray(line_colors)) lc.set_cmap(cmap) lc.set_norm(norm) axes.add_collection(lc) axes.update_datalim(((x.min(), y.min()), (x.max(), y.max()))) axes.autoscale_view(tight=True) ac = matplotlib.collections.PatchCollection(arrows) stream_container = StreamplotSet(lc, ac) return stream_container
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z2 - Z1) # difference of Gaussians # Set up a colormap: palette = cm.gray palette.set_over('r', 1.0) palette.set_under('g', 1.0) palette.set_bad('b', 1.0) # Alternatively, we could use # palette.set_bad(alpha = 0.0) # to make the bad region transparent. This is the default. # If you comment out all the palette.set* lines, you will see # all the defaults; under and over will be colored with the # first and last colors in the palette, respectively. Zm = ma.masked_where(Z > 1.2, Z) # By setting vmin and vmax in the norm, we establish the # range to which the regular palette color scale is applied. # Anything above that range is colored based on palette.set_over, etc. im = imshow(Zm, interpolation='bilinear', cmap=palette, norm=colors.normalize(vmin=-1.0, vmax=1.0, clip=False), origin='lower', extent=[-3, 3, -3, 3]) title('Green=low, Red=high, Blue=bad') colorbar(im, extend='both', shrink=0.8) show()
def plot_atoms(B, breaks, atoms_order, epsj=1e-3, gth=None, lth=None): C = 2 R = len(atoms_order) / C if R * C < len(atoms_order): R += 1 fig = pl.figure(figsize=(10, R)) jumps = atoms_jumps(B, epsj) pl.suptitle('Dictionary Atoms ($B$, jumps=$%d$)' % jumps, weight='bold', size=8) L, J = B.shape # Color boundaries and cmap vmax = np.abs(B).max() vmin = -vmax norm = mlcol.normalize(vmax=vmax, vmin=vmin) cmap = mlcm.RdBu_r #division = np.sqrt(len(atoms_order)) #R, C = int(np.ceil(division)), int(np.floor(division)) for p, d in enumerate(B[:, atoms_order].T): pl.subplot(R, C, p + 1) pl.plot(d, 'k-', lw=1, alpha=0.5) im_ref = pl.scatter(range(len(d)), d, c=d, s=40, marker='.', edgecolors='none', cmap=cmap, norm=norm) vbound = 1.4 #np.abs(d).max()*1.1 pl.axis([0, len(d), -vbound, vbound]) ax = pl.gca() plot_breaks(breaks) add_chr_ticks(ax, breaks, L) ax.yaxis.set_label_position('right') ax.set_ylabel('Atom #%d' % (atoms_order[p] + 1), rotation=-90, size=6, weight='bold') if gth: pl.axhline(gth, c='r') if lth: pl.axhline(lth, c='c') for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(6) tick.tick1On = False tick.tick2On = False for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(6) # Spacing fig.tight_layout() pl.subplots_adjust(top=0.85) # Make an axis for the colorbar on the right side pl.subplots_adjust(right=0.85) cax = fig.add_axes([0.9, 0.1, 0.03, 0.8]) cb = fig.colorbar(im_ref, cax=cax, extend='both') for t in cb.ax.get_yticklabels(): t.set_fontsize(6)
def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None): """Draws streamlines of a vector flow. *x*, *y* : 1d arrays an *evenly spaced* grid. *u*, *v* : 2d arrays x and y-velocities. Number of rows should match length of y, and the number of columns should match x. *density* : float or 2-tuple Controls the closeness of streamlines. When `density = 1`, the domain is divided into a 25x25 grid---*density* linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use [density_x, density_y]. *linewidth* : numeric or 2d array vary linewidth when given a 2d array with the same shape as velocities. *color* : matplotlib color code, or 2d array Streamline color. When given an array with the same shape as velocities, *color* values are converted to colors using *cmap*. *cmap* : :class:`~matplotlib.colors.Colormap` Colormap used to plot streamlines and arrows. Only necessary when using an array input for *color*. *norm* : :class:`~matplotlib.colors.Normalize` Normalize object used to scale luminance data to 0, 1. If None, stretch (min, max) to (0, 1). Only necessary when *color* is an array. *arrowsize* : float Factor scale arrow size. *arrowstyle* : str Arrow style specification. See :class:`~matplotlib.patches.FancyArrowPatch`. *minlength* : float Minimum length of streamline in axes coordinates. Returns ------- *stream_container* : StreamplotSet Container object with attributes lines : `matplotlib.collections.LineCollection` of streamlines arrows : collection of `matplotlib.patches.FancyArrowPatch` objects repesenting arrows half-way along stream lines. This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible. """ grid = Grid(x, y) mask = StreamMask(density) dmap = DomainMap(grid, mask) if color is None: color = axes._get_lines.color_cycle.next() if linewidth is None: linewidth = matplotlib.rcParams['lines.linewidth'] line_kw = {} arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10*arrowsize) use_multicolor_lines = isinstance(color, np.ndarray) if use_multicolor_lines: assert color.shape == grid.shape line_colors = [] else: line_kw['color'] = color arrow_kw['color'] = color if isinstance(linewidth, np.ndarray): assert linewidth.shape == grid.shape line_kw['linewidth'] = [] else: line_kw['linewidth'] = linewidth arrow_kw['linewidth'] = linewidth ## Sanity checks. assert u.shape == grid.shape assert v.shape == grid.shape if np.any(np.isnan(u)): u = np.ma.array(u, mask=np.isnan(u)) if np.any(np.isnan(v)): v = np.ma.array(v, mask=np.isnan(v)) integrate = get_integrator(u, v, dmap, minlength) trajectories = [] for xm, ym in _gen_starting_points(mask.shape): if mask[ym, xm] == 0: xg, yg = dmap.mask2grid(xm, ym) t = integrate(xg, yg) if t != None: trajectories.append(t) if use_multicolor_lines: if norm is None: norm = mcolors.normalize(color.min(), color.max()) if cmap is None: cmap = cm.get_cmap(matplotlib.rcParams['image.cmap']) else: cmap = cm.get_cmap(cmap) streamlines = [] arrows = [] for t in trajectories: tgx = np.array(t[0]) tgy = np.array(t[1]) # Rescale from grid-coordinates to data-coordinates. tx = np.array(t[0]) * grid.dx + grid.x_origin ty = np.array(t[1]) * grid.dy + grid.y_origin points = np.transpose([tx, ty]).reshape(-1, 1, 2) streamlines.extend(np.hstack([points[:-1], points[1:]])) # Add arrows half way along each trajectory. s = np.cumsum(np.sqrt(np.diff(tx)**2 + np.diff(ty)**2)) n = np.searchsorted(s, s[-1] / 2.) arrow_tail = (tx[n], ty[n]) arrow_head = (np.mean(tx[n:n+2]), np.mean(ty[n:n+2])) if isinstance(linewidth, np.ndarray): line_widths = interpgrid(linewidth, tgx, tgy)[:-1] line_kw['linewidth'].extend(line_widths) arrow_kw['linewidth'] = line_widths[n] if use_multicolor_lines: color_values = interpgrid(color, tgx, tgy)[:-1] line_colors.extend(color_values) arrow_kw['color'] = cmap(norm(color_values[n])) p = patches.FancyArrowPatch(arrow_tail, arrow_head, transform=transform, **arrow_kw) axes.add_patch(p) arrows.append(p) lc = mcollections.LineCollection(streamlines, transform=transform, **line_kw) if use_multicolor_lines: lc.set_array(np.asarray(line_colors)) lc.set_cmap(cmap) lc.set_norm(norm) axes.add_collection(lc) axes.update_datalim(((x.min(), y.min()), (x.max(), y.max()))) axes.autoscale_view(tight=True) ac = matplotlib.collections.PatchCollection(arrows) stream_container = StreamplotSet(lc, ac) return stream_container
urcrnrlat=85, resolution='l', projection='cyl', ax=ax) map.drawcoastlines(linewidth=0.5) map.drawrivers(linewidth=0.75, color='white') map.drawparallels(N.arange(-90, 120, 30), labels=[0, 0, 0, 0], linewidth=0.25) map.drawmeridians(N.arange(-720, 750, 30), labels=[0, 0, 0, 0], linewidth=0.25) map.fillcontinents('white') data, x, y = map.transform_scalar(sp_lim, tlon, tlat, nlon, nlat, returnxy=True) IM = map.imshow(data, norm=colors.normalize(vmin=0, vmax=6.5), cmap=cmap) CB = fig.colorbar(IM, ax=ax, shrink=0.5, aspect=12, drawedges=True, ticks=cbticks, boundaries=cblevels, values=cbticks) CB.ax.set_yticklabels(cbticklabels) for line in CB.ax.get_yticklines(): # remove tick lines line.set_markersize(0) bottom_labels(ax, case.replace('_', ' '), '', year_string, fontsize=10) ax.set(title='Small Phyto. growth limitation factor in upper %.0f m' % (zref)) fig.savefig(outfile, dpi=150, bbox_inches='tight', pad_inches=0.2)
def __init__(self, varmin, varmax): self.varmin = varmin self.varmax = varmax self._norm = colors.normalize(varmin, varmax)
outfile = os.path.join(outdir,'map_nutlim_sp.png') else: outfile = os.path.join(outdir,'map_%04d-%04d_nutlim_sp.png'%(yrstart,yrend)) print('plotting %s'%(outfile)) fig = pl.figure() ax = fig.add_subplot(111) map = Basemap(llcrnrlon=30,urcrnrlon=360+30,llcrnrlat=-85,urcrnrlat=85, resolution='l',projection='cyl',ax=ax) map.drawcoastlines(linewidth=0.5) map.drawrivers(linewidth=0.75,color='white') map.drawparallels(N.arange(-90,120,30),labels=[0,0,0,0],linewidth=0.25) map.drawmeridians(N.arange(-720,750,30),labels=[0,0,0,0],linewidth=0.25) map.fillcontinents('white') data, x, y = map.transform_scalar(sp_lim,tlon,tlat,nlon,nlat,returnxy=True) IM = map.imshow(data,norm=colors.normalize(vmin=0,vmax=6.5),cmap=cmap) CB = fig.colorbar(IM,ax=ax,shrink=0.5,aspect=12,drawedges=True,ticks=cbticks, boundaries=cblevels,values=cbticks) CB.ax.set_yticklabels(cbticklabels) for line in CB.ax.get_yticklines(): # remove tick lines line.set_markersize(0) bottom_labels(ax,case.replace('_',' '),'',year_string,fontsize=10) ax.set(title='Small Phyto. growth limitation factor in upper %.0f m'%(zref)) fig.savefig(outfile,dpi=150,bbox_inches='tight',pad_inches=0.2) pl.close(fig) # Diatom nutrient limitation plot if POPDIAGPY == 'TRUE': outfile = os.path.join(outdir,'map_nutlim_diat.png') else:
for i,crow in enumerate(indat): indat[i][0] = indat[i][0].lower() for clay in lays: cfig = plt.figure() ax1 = cfig.add_subplot(111) plt.hold=True plotcol = [] plotrow = [] plotval = [] for crow in indat: if int(crow[0][3])==clay: plotcol.append(lox_dict[crow[0]][1]) plotrow.append(lox_dict[crow[0]][0]) plotval.append((crow[2]-crow[3])**2) plotcol = np.array(plotcol) plotrow = np.array(plotrow) plotval = np.array(plotval) plt.scatter(plotcol, plotrow, cmap = cm.jet, norm=cols.normalize(0), s=plotval*1e4, c=plotval) plt.xlim((1,35)) plt.ylim((40,1)) plt.axis('equal') cb=plt.colorbar() plt.title('Residuals for layer ' +str(clay)) plt.savefig(cmod + '_residuals_lay_' + str(clay) + '.pdf')
def colorflood(gridobject, arr, **kwargs): """ Method for color flooding an array for a Modflow grid. """ #imports import matplotlib.cm as cm import matplotlib.colors as colors from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection #set defaults from kwargs ax = matplotlib.pyplot.gca() arrexclude = [] arrmin = arr.min() arrmax = arr.max() alpha = 1.0 cb = False if kwargs.has_key('ax'): ax = kwargs['ax'] if kwargs.has_key('arrexclude'): arrexclude = kwargs['arrexclude'] if kwargs.has_key('arrmin'): arrmin = kwargs['arrmin'] if kwargs.has_key('arrmax'): arrmax = kwargs['arrmax'] if kwargs.has_key('alpha'): alpha = kwargs['alpha'] if kwargs.has_key('cb'): cb = kwargs['cb'] #plot colorbar? norm = colors.normalize(arrmin, arrmax) patches = [] for nodenumber in range(gridobject.nodes): nodeobj = gridobject.get_nodeobj(nodenumber) (k, i, j) = gridobject.get_indices(nodenumber) x, y = nodeobj.position[0], nodeobj.position[1] dx, dy = nodeobj.dxdydz[0], nodeobj.dxdydz[1] xmin = x - dx / 2. xmax = x + dx / 2. ymin = y - dy / 2. ymax = y + dy / 2. vertices = [ (xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)] if arr[k, i, j] in arrexclude: #cannot get visible and alpha to work, so this is the hack. vertices = [(0,0), (0,0), (0,0), (0,0) ] poly = Polygon(vertices, linewidth=0., fc = None, ec='none') patches.append(poly) #set up the patchcollection for faster coloring p = PatchCollection(patches, match_original=True) p.set_array(arr.reshape(-1)) p.set_norm(norm) p.set_edgecolor(None) p.set_alpha(alpha) ax.add_collection(p) #create the colorbar if cb: pc = [] color = cm.jet(norm(arrmin)) poly = Polygon( ((0,0), (1,0), (1,1), (0,1)), linewidth=0., fc = color, ec='none', alpha=0.4) pc.append(poly) color = cm.jet(norm(arrmax)) poly = Polygon( ((0,0), (1,0), (1,1), (0,1)), linewidth=0., fc = color, ec='none', alpha=0.4) pc.append(poly) p = PatchCollection(pc, match_original=True) p.set_array(numpy.array([arrmin, arrmax])) matplotlib.pyplot.colorbar(p, shrink=0.5) return
def plot_3D_SWC(file_name='P20-DEV139.CNG.swc', cs=None, synapses=None, outN=None): """ Matplotlib rendering of a SWC described morphology in 3D Colors can be None: uniform/default matplotlib color Any color code: uniform but specified color array of values: colormap? """ my_color_list = ['r', 'g', 'b', 'c', 'm', 'y', 'r--', 'b--', 'g--'] if (cs == None): pass else: norm = colors.normalize(np.min(cs), np.max(cs)) Z = [[0, 0], [0, 0]] levels = range(int(np.min(cs)), int(np.max(cs)), 1) levels = np.linspace(np.min(cs), np.max(cs), 1) CS3 = plt.contourf(Z, levels, cmap=cm.jet) plt.clf() # read the SWC into a dictionary: key=index, value=(x,y,z,d,parent) x = open(file_name, 'r') SWC = {} for line in x: if (not line.startswith('#')): splits = line.split() index = int(splits[0]) n_type = int(splits[1]) x = float(splits[2]) y = float(splits[3]) z = float(splits[4]) r = float(splits[5]) parent = int(splits[-1]) SWC[index] = (x, y, z, r, parent, n_type) fig = plt.figure() ax = fig.gca(projection='3d') for index in SWC.keys(): # not ordered but that has little importance here # draw a line segment from parent to current point current_SWC = SWC[index] #print 'index: ', index, ' -> ', current_SWC c_x = current_SWC[0] c_y = current_SWC[1] c_z = current_SWC[2] c_r = current_SWC[3] parent_index = current_SWC[4] if (index <= 3): print 'do not draw the soma and its CNG, !!! 2 !!! point descriptions' else: parent_SWC = SWC[parent_index] p_x = parent_SWC[0] p_y = parent_SWC[1] p_z = parent_SWC[2] p_r = parent_SWC[3] # print 'index:', index, ', len(cs)=', len(cs) if cs == None: pl = plt.plot([p_x, c_x], [p_y, c_y], [p_z, c_z], my_color_list[current_SWC[5] - 1], linewidth=c_r) else: try: pl = plt.plot([p_x,c_x],[p_y,c_y], \ c=cm.jet(norm(cs[index])),linewidth=c_r) except Exception: print 'something going wrong here' # pass# it's ok: it's the list size... # add the synapses if (synapses != None): if (index in synapses): plt.plot(c_x, c_y, 'ro') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') if (cs != None): cb = plt.colorbar(CS3) # bit of a workaround, but it seems to work ticks_f = np.linspace(np.min(cs) - 1, np.max(cs) + 1, 5) ticks_i = map(int, ticks_f) cb.set_ticks(ticks_i) if (outN != None): plt.savefig(outN)
# use major and minor sphere radii from WGS84 ellipsoid. m = Basemap(llcrnrlon=-145.5,llcrnrlat=1.,urcrnrlon=-2.566,urcrnrlat=46.352,\ rsphere=(6378137.00,6356752.3142),\ resolution='l',area_thresh=1000.,projection='lcc',\ lat_1=50.,lon_0=-107.) # transform to nx x ny regularly spaced native projection grid nx = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1 topodat,x,y = m.transform_scalar(topoin,lonsin,latsin,nx,ny,returnxy=True) # set up figure with same aspect ratio as map. fig=m.createfigure() ax = fig.add_axes([0.1,0.1,0.7,0.7],axisbg='aqua') # make topodat a masked array, masking values lower than sea level. topodat = where(topodat < 0.,1.e10,topodat) topodat = ma.masked_values(topodat, 1.e10) # plot image over map with imshow. im = m.imshow(topodat,cm.jet,norm=colors.normalize(vmin=-4000.0,vmax=3000.0,clip=False)) cax = axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes colorbar(tickfmt='%d', cax=cax) # draw colorbar axes(ax) # make the original axes current again # plot blue dot on boulder, colorado and label it as such. xpt,ypt = m(-104.237,40.125) m.plot([xpt],[ypt],'bo') text(xpt+100000,ypt+100000,'Boulder') # draw coastlines and political boundaries. m.drawcoastlines() m.drawcountries() m.drawstates() # draw parallels and meridians. # label on left, right and bottom of map. parallels = arange(0.,80,20.) m.drawparallels(parallels,labels=[1,1,0,1])
def st(self, sx, sy, sz, spin=None, noarrow=False, interpolation=250): """Only 2D layer geometry along z. It is like a enhanced version of 'plot' method. sx, sy, sz are spin projected Nkpoints x Nbands numpy arrays. They also are (already) projected by orbital and atom (from other class) """ self.log.debug("st: ...") from scipy.interpolate import griddata, interp2d, BivariateSpline if self.useful is None: raise RuntimeError( "self.FindEnergy() must be called before Plotting") #selecting components of K-points x, y = self.kpoints[:, 0], self.kpoints[:, 1] bands = self.bands.transpose()[self.useful] sx = sx.transpose()[self.useful] sy = sy.transpose()[self.useful] sz = sz.transpose()[self.useful] #and new, interpolated component xmax, xmin = x.max(), x.min() ymax, ymin = y.max(), y.min() if (noarrow): interpolation = interpolation * 50 self.log.debug("xlim = " + str([xmin, xmax]) + " ylim = " + str([ymin, ymax])) xnew, ynew = np.mgrid[xmin:xmax:interpolation * 1j, ymin:ymax:interpolation * 1j] #interpolation bnew = [] for band in bands: self.log.debug("Interpolating ...") bnew.append(griddata((x, y), band, (xnew, ynew), method='cubic')) linewidths = 0.7 if noarrow: linewidths = 0.2 cont = [ plt.contour(xnew, ynew, z, [self.energy], linewidths=linewidths, colors='k', linestyles='solid') for z in bnew ] plt.axis("equal") for (contour, spinX, spinY, spinZ) in zip(cont, sx, sy, sz): # The previous interp. yields the level curves, nothing more is # useful from there paths = contour.collections[0].get_paths() verts = [xx.vertices for xx in paths] points = np.concatenate(verts) self.log.debug("Fermi surf. points.shape: " + str(points.shape)) newSx = griddata((x, y), spinX, (points[:, 0], points[:, 1])) newSy = griddata((x, y), spinY, (points[:, 0], points[:, 1])) newSz = griddata((x, y), spinZ, (points[:, 0], points[:, 1])) self.log.info("newSx.shape: " + str(newSx.shape)) import matplotlib.colors as colors if noarrow is False: norm = np.sqrt(newSx[::6] * newSx[::6] + newSy[::6] * newSy[::6]) plt.quiver(points[::6, 0], points[::6, 1], newSx[::6] / norm, newSy[::6] / norm, norm, scale_units='xy', angles='xy', norm=colors.Normalize(-0.5, 0.5), cmap='seismic_r', headaxislength=3) else: #a dictionary to select the right spin component spinDict = {1: newSx[::6], 2: newSy[::6], 3: newSz[::6]} plt.scatter(points[::6, 0], points[::6, 1], c=spinDict[spin], s=50, edgecolor='none', alpha=1.0, marker=".", cmap='seismic', norm=colors.normalize(-0.5, 0.5)) plt.colorbar() plt.axis("equal") font = {'size': 16} plt.rc('font', **font) self.log.debug("st: ...Done") return
def plot_3D_SWC(file_name='P20-DEV139.CNG.swc',cs=None,synapses=None,outN=None) : """ Matplotlib rendering of a SWC described morphology in 3D Colors can be None: uniform/default matplotlib color Any color code: uniform but specified color array of values: colormap? """ my_color_list = ['r','g','b','c','m','y','r--','b--','g--'] if(cs == None) : pass else : norm = colors.normalize(np.min(cs),np.max(cs)) Z = [[0,0],[0,0]] levels=range(int(np.min(cs)),int(np.max(cs)),1) levels = np.linspace(np.min(cs),np.max(cs),1) CS3 = plt.contourf(Z,levels,cmap=cm.jet) plt.clf() # read the SWC into a dictionary: key=index, value=(x,y,z,d,parent) x = open(file_name,'r') SWC = {} for line in x : if(not line.startswith('#')) : splits = line.split() index = int(splits[0]) n_type = int(splits[1]) x = float(splits[2]) y = float(splits[3]) z = float(splits[4]) r = float(splits[5]) parent = int(splits[-1]) SWC[index] = (x,y,z,r,parent,n_type) fig = plt.figure() ax = fig.gca(projection='3d') for index in SWC.keys() : # not ordered but that has little importance here # draw a line segment from parent to current point current_SWC = SWC[index] #print 'index: ', index, ' -> ', current_SWC c_x = current_SWC[0] c_y = current_SWC[1] c_z = current_SWC[2] c_r = current_SWC[3] parent_index = current_SWC[4] if(index <= 3) : print 'do not draw the soma and its CNG, !!! 2 !!! point descriptions' else : parent_SWC = SWC[parent_index] p_x = parent_SWC[0] p_y = parent_SWC[1] p_z = parent_SWC[2] p_r = parent_SWC[3] # print 'index:', index, ', len(cs)=', len(cs) if cs == None : pl = plt.plot([p_x,c_x],[p_y,c_y],[p_z,c_z],my_color_list[current_SWC[5]-1],linewidth=c_r) else : try : pl = plt.plot([p_x,c_x],[p_y,c_y], \ c=cm.jet(norm(cs[index])),linewidth=c_r) except Exception : print 'something going wrong here' # pass# it's ok: it's the list size... # add the synapses if(synapses != None) : if(index in synapses) : plt.plot(c_x,c_y,'ro') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') if(cs != None) : cb = plt.colorbar(CS3) # bit of a workaround, but it seems to work ticks_f = np.linspace(np.min(cs)-1,np.max(cs)+1,5) ticks_i = map(int,ticks_f) cb.set_ticks(ticks_i) if(outN != None) : plt.savefig(outN)
source = zip(*source)[1] data = map(float, source) ##### py.clf() # fig=py.figure() # ax = fig.add_subplot(111) n, bins, patches = py.hist(data, bins=50, range=(0,1), normed=True, alpha=0.75) # normalizacja do 1 locs,labels = py.yticks() py.yticks(locs[1:], map(lambda x: "%.2f" % (x/sum(n)), locs[1:])) fracs = n.astype(float)/n.max() norm = colors.normalize(0, 1) for thisfrac, thispatch in zip(fracs, patches): color = cm.jet(norm(thisfrac)) thispatch.set_facecolor(color) py.xlabel('Percentage of labeled zones') py.ylabel('Documents in bin') py.title('Histogram of labeled zones') py.savefig('hist.pdf', transparent = True) py.show() ##### n, bins, patches = py.hist(data, 50, range=(0,1), normed=True, cumulative=1, alpha=0.75) fracs = 1-n.astype(float)/n.max()
# transform to nx x ny regularly spaced native projection grid nx = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1 topodat,x,y = m.transform_scalar(topoin,lonsin,latsin,nx,ny,returnxy=True) # create the figure. fig=plt.figure(figsize=(8,8)) # add an axes, leaving room for colorbar on the right. ax = fig.add_axes([0.1,0.1,0.7,0.7]) # associate this axes with the Basemap instance. m.ax = ax # make topodat a masked array, masking values lower than sea level. topodat = np.where(topodat < 0.,1.e10,topodat) topodatm = ma.masked_values(topodat, 1.e10) palette = plt.cm.YlOrRd palette.set_bad('aqua', 1.0) # plot image over map with imshow. im = m.imshow(topodatm,palette,norm=colors.normalize(vmin=0.0,vmax=3000.0,clip=False)) # setup colorbar axes instance. pos = ax.get_position() l, b, w, h = pos.bounds cax = plt.axes([l+w+0.075, b, 0.05, h]) plt.colorbar(im,cax=cax) # draw colorbar # plot blue dot on boulder, colorado and label it as such. xpt,ypt = m(-104.237,40.125) m.plot([xpt],[ypt],'bo') ax.text(xpt+100000,ypt+100000,'Boulder') # draw coastlines and political boundaries. m.drawcoastlines() m.drawcountries() m.drawstates() # draw parallels and meridians. # label on left, right and bottom of map.
returnxy=True) # create the figure. fig = plt.figure(figsize=(8, 8)) # add an axes. ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # associate this axes with the Basemap instance. m.ax = ax # make topodat a masked array, masking values lower than sea level. topodat = np.where(topodat < 0., 1.e10, topodat) topodatm = ma.masked_values(topodat, 1.e10) palette = plt.cm.YlOrRd palette.set_bad('aqua', 1.0) # plot image over map with imshow. im = m.imshow(topodatm, palette, norm=colors.normalize(vmin=0.0, vmax=3000.0, clip=False)) m.colorbar(im, pad='12%') # draw colorbar # plot blue dot on boulder, colorado and label it as such. xpt, ypt = m(-104.237, 40.125) m.plot([xpt], [ypt], 'bo') ax.text(xpt + 100000, ypt + 100000, 'Boulder') # draw coastlines and political boundaries. m.drawcoastlines() m.drawcountries() m.drawstates() # draw parallels and meridians. # label on left, right and bottom of map. parallels = np.arange(0., 80, 20.) m.drawparallels(parallels, labels=[1, 1, 0, 1]) meridians = np.arange(10., 360., 30.) m.drawmeridians(meridians, labels=[1, 1, 0, 1])
for i, crow in enumerate(indat): indat[i][0] = indat[i][0].lower() for clay in lays: cfig = plt.figure() ax1 = cfig.add_subplot(111) plt.hold = True plotcol = [] plotrow = [] plotval = [] for crow in indat: if int(crow[0][3]) == clay: plotcol.append(lox_dict[crow[0]][1]) plotrow.append(lox_dict[crow[0]][0]) plotval.append((crow[2] - crow[3])**2) plotcol = np.array(plotcol) plotrow = np.array(plotrow) plotval = np.array(plotval) plt.scatter(plotcol, plotrow, cmap=cm.jet, norm=cols.normalize(0), s=plotval * 1e4, c=plotval) plt.xlim((1, 35)) plt.ylim((40, 1)) plt.axis('equal') cb = plt.colorbar() plt.title('Residuals for layer ' + str(clay)) plt.savefig(cmod + '_residuals_lay_' + str(clay) + '.pdf')
def draw_3d_bar_chart(samples, top_level_names=None, second_level_names=None, title=None, xlabel=None, ylabel=None, zlabel=None, flip_y=True, third_level_names=None): # So, samples can either contain a list of lists. The top level list # contains top level groups, and the second level list contains actual # samples (top_level_grouping_only = true) # Alternatively, samples may be a list of lists of lists, with top-level # groups, second level groups and actual samples. (top_level_grouping_only) means = [] confs = [] second_level_grouping_available = \ isinstance(samples[0][0], collections.Sequence) top_level_methods = len(samples) if second_level_grouping_available: second_level_methods = len(samples[0]) samples2 = samples else: # Create artificial second level grouping second_level_methods = 1 samples2 = [[samples[i]] for i in range(top_level_methods)] for i in range(top_level_methods): means.append([]) confs.append([]) for i in range(top_level_methods): for j in range(second_level_methods): m, h = calculate_mean_and_standard_error(samples[i][j]) means[i].append(m) confs[i].append(h) ind = np.arange(second_level_methods) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') rects = [] xpos = np.array([]) ypos = np.array([]) zpos = np.array([]) dx = np.array([]) dy = np.array([]) dz = np.array([]) for j in range(second_level_methods): for i in range(top_level_methods): xpos = np.append(xpos, i) if flip_y: ypos = np.append(ypos, second_level_methods - j - 1) else: ypos = np.append(ypos, j) zpos = np.append(zpos, 0) dx = np.append(dx, 1.0) dy = np.append(dy, 0.5) dz = np.append(dz, means[i][j]) #http://stackoverflow.com/questions/11950375/apply-color-map-to-mpl-toolkits-mplot3d-axes3d-bar3d offset = dz + np.abs(dz.min()) fracs = offset.astype(float) / offset.max() norm = colors.normalize(fracs.min(), fracs.max()) colors_t = cm.jet(norm(fracs) / 2 + 0.5) # for xs, ys, zs, dxs, dys, dzs, colors_ts in zip(xpos, ypos, zpos, dx, dy, dz, colors_t): # rects.append(ax.bar3d(xs, ys, zs, dxs, dys, dzs, color=colors_ts, zsort='')) rects = ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors_t, zsort=True) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) if zlabel: ax.set_zlabel(zlabel) if title: ax.set_title(title) if second_level_grouping_available: ax.set_yticks(ind + 0.5) if second_level_names: if flip_y: second_level_names.reverse() ax.set_yticklabels(second_level_names) if third_level_names: ax.set_zticklabels(third_level_names) tick_multiplier = int( math.ceil(float(top_level_methods) / float(len(top_level_names)))) ax.set_xticks(tick_multiplier * np.arange(len(top_level_names)) + 0.5) xtickrotation = raw_input( "Specify rotation for xticklabels [hit enter to use zero]: ") if xtickrotation is not None and xtickrotation != "": xtickrotation = float(xtickrotation) else: xtickrotation = 0.0 if top_level_names: ax.set_xticklabels(top_level_names, rotation=xtickrotation) # ax.legend(rects, top_level_names, mode='expand', ncol=3) return fig, ax, rects, means
def time_freq_plot(database, instrument, sim): fig = SnglBurstUtils.figure.Figure() SnglBurstUtils.FigureCanvas(fig) # 6.5" wide, golden ratio high fig.set_size_inches(6.5, 6.5 / ((1 + math.sqrt(5)) / 2)) # # top plot --- triggers that matched injection # t_sim = sim.time_at_instrument(instrument) axes = fig.add_subplot(211) axes.grid(True) #axes.set_xlabel("$t - t_{\mathrm{injection}}$ (s)") axes.set_ylabel("$f - f_{\mathrm{injection}}$ (Hz)") axes.set_title("%s Triggers Matching %g Hz Injection at GPS %s" % (instrument, sim.frequency, t_sim)) xmin = xmax = 0.0 ymin = ymax = 0.0 verts = [] colours = [] peakx = [] peaky = [] match_ids = [] # find triggers from the desired instrument that are coincident # with the injection, and iterate over them in order from least to # most confident for burst in map( database.sngl_burst_table.row_from_cols, database.connection.cursor().execute( """ SELECT sngl_burst.* FROM sngl_burst JOIN coinc_event_map AS a ON ( sngl_burst.event_id == a.event_id AND a.table_name == 'sngl_burst' ) JOIN coinc_event_map AS b ON ( a.coinc_event_id == b.coinc_event_id AND b.table_name == 'sim_burst' ) WHERE sngl_burst.ifo == ? AND b.event_id == ? ORDER BY sngl_burst.confidence ASC """, (instrument, sim.simulation_id))): match_ids.append(burst.event_id) # Add time-frequency tile to collection tmin = float(burst.start - t_sim) tmax = float(burst.start + burst.duration - t_sim) fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency verts.append(((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax))) colours.append(burst.confidence) try: # draw most significant tile if there is one tmin = float(burst.ms_start - t_sim) tmax = float(burst.ms_start + burst.ms_duration - t_sim) fmin = burst.ms_flow - sim.frequency fmax = burst.ms_flow + burst.ms_bandwidth - sim.frequency verts.append( ((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax))) colours.append(burst.ms_confidence) except AttributeError: pass peakx.append(float(burst.peak - t_sim)) try: # use peak_frequency col if it exists peaky.append(burst.peak_frequency - sim.frequency) except AttributeError: peaky.append(burst.central_freq - sim.frequency) # update bounding box tmin = float(burst.start - t_sim) tmax = float(burst.start + burst.duration - t_sim) fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency xmin = min(xmin, tmin) xmax = max(xmax, tmax) ymin = min(ymin, fmin) ymax = max(ymax, fmax) polys = collections.PolyCollection(verts) polys.set_array(numpy.array(colours)) polys.set_alpha(0.3) polys.set_cmap(cm.get_cmap()) polys.set_norm(colors.normalize()) axes.add_collection(polys) axes.plot(peakx, peaky, "k+") axes.axvline(0, color="k") axes.axhline(0, color="k") # set the bounding box axes.set_xlim([1.4 * xmin, 1.4 * xmax]) axes.set_ylim([1.4 * ymin, 1.4 * ymax]) # # bottom plot --- triggers near injection # axes = fig.add_subplot(212) axes.grid(True) axes.set_xlabel("$t - t_{\mathrm{injection}}$ (s)") axes.set_ylabel("$f - f_{\mathrm{injection}}$ (Hz)") xmin = xmax = 0.0 ymin = ymax = 0.0 verts = [] colours = [] edgecolours = [] peakx = [] peaky = [] # find triggers from the desired instrument that are near the # injection, and iterate over them in order from least to most # confident for burst in map( database.sngl_burst_table.row_from_cols, database.connection.cursor().execute( """ SELECT * FROM sngl_burst WHERE ifo == ? AND start_time BETWEEN ? AND ? AND central_freq BETWEEN ? AND ? ORDER BY sngl_burst.confidence ASC """, (instrument, int(t_sim - 2), int(t_sim + 2), sim.frequency - 300, sim.frequency + 300))): # Add time-frequency tile to collection tmin = float(burst.start - t_sim) tmax = float(burst.start + burst.duration - t_sim) fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency verts.append(((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax))) colours.append(burst.confidence) if burst.event_id in match_ids: edgecolours.append("g") else: edgecolours.append("k") peakx.append(float(burst.peak - t_sim)) try: # use peak_frequency col if it exists peaky.append(burst.peak_frequency - sim.frequency) except: peaky.append(burst.central_freq - sim.frequency) # update bounding box xmin = min(xmin, tmin) xmax = max(xmax, tmax) ymin = min(ymin, fmin) ymax = max(ymax, fmax) polys = collections.PolyCollection(verts, edgecolors=edgecolours) polys.set_array(numpy.array(colours)) polys.set_alpha(0.3) polys.set_cmap(cm.get_cmap()) polys.set_norm(colors.normalize()) axes.add_collection(polys) axes.plot(peakx, peaky, "k+") axes.axvline(0, color="k") axes.axhline(0, color="k") # set the bounding box axes.set_xlim([1.4 * xmin, 1.4 * xmax]) axes.set_ylim([1.4 * ymin, 1.4 * ymax]) return fig
def read(file, sym, minimum, maximum, step): data = ic.columnfile('%s.gff' % file) #grain sizes if "grainno" not in data.titles: data.addcolumn(data.grain_id, 'grainno') if "grainvolume" in data.titles: scale = max(data.grainvolume**0.3333) data.addcolumn(data.grainvolume**0.3333 / scale * 100, 'size') else: data.addcolumn(100. * np.ones(data.nrows), 'size') rodx = [] rody = [] rodz = [] if "rodx" not in data.titles: for i in range(data.nrows): U = np.array([[data.U11[i], data.U12[i], data.U13[i]], [data.U21[i], data.U22[i], data.U23[i]], [data.U31[i], data.U32[i], data.U33[i]]]) rod = tools.u_to_rod(U) rodx.append(rod[0]) rody.append(rod[1]) rodz.append(rod[2]) data.addcolumn(np.array(rodx), 'rodx') data.addcolumn(np.array(rody), 'rody') data.addcolumn(np.array(rodz), 'rodz') if sym == "standard": #grain colours, so that all orientations in Cubic space are allowed maxhx = 62.8 * 3.14 / 180 minhx = -62.8 * 3.14 / 180 maxhy = 62.8 * 3.14 / 180 minhy = -62.8 * 3.14 / 180 maxhz = 62.8 * 3.14 / 180 minhz = -62.8 * 3.14 / 180 rr = data.rodx**2 + data.rody**2 + data.rodz**2 rr = np.sqrt(rr) theta = 2 * np.arctan(rr) r1 = data.rodx / rr r2 = data.rody / rr r3 = data.rodz / rr # normalise colours red = (r1 * theta - minhx) / (maxhx - minhx) green = (r2 * theta - minhy) / (maxhy - minhy) blue = (r3 * theta - minhz) / (maxhz - minhz) elif sym == "orthorhombic": # Fill orthorhombic stereographic triangle red = [] green = [] blue = [] fig = pl.figure(10, frameon=False, figsize=pl.figaspect(1.0)) ax = pl.Axes(fig, [.2, .2, .7, .7]) ax.set_axis_off() fig.add_axes(ax) #plot triangle xa = np.zeros((101)) ya = np.zeros((101)) for i in range(101): xa[i] = np.cos(i * np.pi / 200.) ya[i] = np.sin(i * np.pi / 200.) pl.plot(xa, ya, 'black') # Curved edge pl.plot([0, 1], [0, 0], 'black', linewidth=2) #lower line pl.plot([0, 0], [1, 0], 'black', linewidth=2) #left line pl.text(-0.02, -0.04, '[001]') pl.text(0.95, -0.04, '[100]') pl.text(-0.02, 1.01, '[010]') # Grains for i in range(data.nrows): U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]]) axis = abs(U[2, :]) colour = np.zeros((3)) colour[0] = (2 * np.arcsin(abs(axis[2])) / np.pi)**1 colour[1] = (2 * np.arcsin(abs(axis[0])) / np.pi)**1 colour[2] = (2 * np.arcsin(abs(axis[1])) / np.pi)**1 mx = max(colour) colour = colour / mx red.append(colour[0]) green.append(colour[1]) blue.append(colour[2]) X = axis[0] / (1 + axis[2]) Y = axis[1] / (1 + axis[2]) pl.plot(X, Y, 'o', color=colour) pl.xlim() elif sym == "cubic": # Fill cubic stereographic triangle red = [] green = [] blue = [] fig = pl.figure(10, frameon=False, figsize=pl.figaspect(.9)) ax = pl.Axes(fig, [.2, .2, .7, .7]) ax.set_axis_off() fig.add_axes(ax) #plot triangle xa = np.zeros((21)) ya = np.zeros((21)) for i in range(21): ua = np.array([i / 20., 1., 1.]) UA = np.linalg.norm(ua) za = ua[2] + UA xa[i] = ua[1] / za ya[i] = ua[0] / za pl.plot(xa, ya, 'black') # Curved edge pl.plot([0, xa[0]], [0, 0.0001], 'black', linewidth=2) #lower line pl.plot([xa[20], 0], [ya[20], 0], 'black') # upper line pl.text(-0.01, -0.02, '[100]') pl.text(xa[0] - 0.01, -0.02, '[110]') pl.text(xa[-1] - 0.01, ya[-1] + 0.005, '[111]') # Grains for i in range(data.nrows): U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]]) axis = abs(U[2, :]) colour = np.zeros((3)) for j in range(3): for k in range(j + 1, 3): if (axis[j] > axis[k]): colour[0] = axis[j] axis[j] = axis[k] axis[k] = colour[0] rr = np.sqrt(axis[0] * axis[0] / ((axis[2] + 1)) / ((axis[2] + 1)) + (axis[1] / (axis[2] + 1) + 1) * (axis[1] / (axis[2] + 1) + 1)) if axis[1] == 0: beta = 0 else: beta = np.arctan(axis[0] / axis[1]) colour[0] = ((np.sqrt(2.0) - rr) / (np.sqrt(2.0) - 1))**.5 colour[1] = ((1 - 4 * beta / np.pi) * ((rr - 1) / (np.sqrt(2.0) - 1)))**.5 colour[2] = (4 * beta / np.pi * ((rr - 1) / (np.sqrt(2.0) - 1)))**.5 mx = max(colour) colour = colour / mx red.append(colour[0]) green.append(colour[1]) blue.append(colour[2]) X = axis[1] / (1 + axis[2]) Y = axis[0] / (1 + axis[2]) pl.plot(X, Y, 'o', color=colour) pl.xlim() elif sym == "hexagonal": ## Fill hexagonal stereographic triangle A = np.array([[0, 1, 0], [0, -np.sqrt(3), 1], [1, 0, 0]]) a0 = 1. / np.sqrt(3.) a1 = 1. a2 = 1. red = [] green = [] blue = [] fig = pl.figure(10, frameon=False, figsize=pl.figaspect(0.5)) ax = pl.Axes(fig, [0.2, .2, 0.6, 0.6]) ax.set_axis_off() fig.add_axes(ax) ## Plot triangle ya = np.array(list(range(51))) / 100. xa = np.sqrt(1 - ya**2) pl.plot(xa, ya, 'black') # Curved edge pl.plot([0, xa[0]], [0, 0.0001], 'black', linewidth=2) #lower line pl.plot([xa[-1], 0], [ya[-1], 0], 'black') # upper line ## Label crystalographic directions pl.text(-0.01, -0.02, '[0001]') pl.text(xa[0] - 0.03, -0.02, '[2-1-10]') pl.text(xa[-1] - 0.03, ya[-1] + 0.005, '[10-10]') ## Grains r = symmetry.rotations(6) for i in range(data.nrows): U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]]) square = 1 angle = 0 frac = 1. / np.sqrt(3.) for k in range(len(r)): g = np.dot(U, r[k]) a = np.arccos((np.trace(g) - 1) / 2) if g[2, 2] > 0: uvw = g[2, :] else: uvw = -g[2, :] ## needed to switch these indices to get correct color and inv pf location switch1 = uvw[0] switch2 = uvw[1] uvw[0] = switch2 uvw[1] = switch1 x = uvw[0] / (1 + uvw[2]) y = uvw[1] / (1 + uvw[2]) f = y / x s = x * x + y * y ## Finds r (symmetry) which plots grain into triangle if f <= frac and s <= square and x >= 0 and y >= 0: angle = a frac = f square = s UVW = uvw X = x Y = y colour = np.dot(np.transpose(A), np.transpose(UVW))**0.7 colour[0] = colour[0] / a2 colour[1] = colour[1] / a1 colour[2] = colour[2] / a0 mx = max(colour) colour = colour / mx red.append(colour[0]) green.append(colour[1]) blue.append(colour[2]) pl.plot(X, Y, 'o', color=colour) pl.xlim() elif sym == "e11": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps11_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse strain:", np.sum(data.grainvolume * data.eps11_s) / np.sum(data.grainvolume)) elif sym == "e22": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps22_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse strain:", np.sum(data.grainvolume * data.eps22_s) / np.sum(data.grainvolume)) elif sym == "e33": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps33_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "axial strain:", np.sum(data.grainvolume * data.eps33_s) / np.sum(data.grainvolume)) elif sym == "e12": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps12_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear strain:", np.sum(data.grainvolume * data.eps12_s) / np.sum(data.grainvolume)) elif sym == "e13": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps13_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear strain:", np.sum(data.grainvolume * data.eps13_s) / np.sum(data.grainvolume)) elif sym == "e23": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps23_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear strain:", np.sum(data.grainvolume * data.eps23_s) / np.sum(data.grainvolume)) elif sym == "s33": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 150, 50, 'MPa') norm = colors.normalize(-50, 150) color = cm.jet(norm(data.sig33_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "axial stress:", np.sum(data.grainvolume * data.sig33_s) / np.sum(data.grainvolume), "MPa") elif sym == "s11": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 150, 50, 'MPa') norm = colors.normalize(-50, 150) color = cm.jet(norm(data.sig11_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse s11 stress:", np.sum(data.grainvolume * data.sig11_s) / np.sum(data.grainvolume), "MPa") elif sym == "s22": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 150, 50, 'MPa') norm = colors.normalize(-50, 150) color = cm.jet(norm(data.sig22_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse s22 stress:", np.sum(data.grainvolume * data.sig22_s) / np.sum(data.grainvolume), "MPa") elif sym == "s12": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 50, 50, 'MPa') norm = colors.normalize(-50, 50) color = cm.jet(norm(data.sig12_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear s12 stress:", np.sum(data.grainvolume * data.sig12_s) / np.sum(data.grainvolume), "MPa") elif sym == "s13": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 50, 50, 'MPa') norm = colors.normalize(-50, 50) color = cm.jet(norm(data.sig13_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear s13 stress:", np.sum(data.grainvolume * data.sig13_s) / np.sum(data.grainvolume), "MPa") elif sym == "s23": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 50, 50, 'MPa') norm = colors.normalize(-50, 50) color = cm.jet(norm(data.sig23_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear s23 stress:", np.sum(data.grainvolume * data.sig23_s) / np.sum(data.grainvolume), "MPa") elif sym == "latt_rot": norm = colors.normalize(0, 0.5) color = cm.jet(norm(data.latt_rot)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] colourbar(0.0, 0.5, 0.1, 'deg') elif sym == "tz": norm = colors.normalize(-0.1, 0.1) color = cm.jet(norm(data.tz)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] elif sym == "vol": norm = colors.normalize(0, 10) color = cm.jet(norm(data.grainvolume / data.d_grainvolume)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] elif sym == "tth": norm = colors.normalize(0.007, 0.009) color = cm.jet(norm(data.sig_tth / data.grainvolume**.2)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print(min(data.sig_tth / data.grainvolume**.2), max(data.sig_tth / data.grainvolume**.2)) # pl.figure(8) # pl.plot(np.log(data.grainvolume),np.log(data.sig_tth),'.') elif sym == "eta": norm = colors.normalize(0.08, 0.15) color = cm.jet(norm(data.sig_eta / data.grainvolume**.2)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print(min(data.sig_eta / data.grainvolume**.2), max(data.sig_eta / data.grainvolume**.2)) # pl.figure(8) # pl.plot(np.log(data.grainvolume),np.log(data.sig_eta),'.') else: np.random.seed(0) red = np.random.rand(data.nrows) np.random.seed(1) green = np.random.rand(data.nrows) np.random.seed(2) blue = np.random.rand(data.nrows) data.addcolumn(red, 'red') data.addcolumn(green, 'green') data.addcolumn(blue, 'blue') return (data)
for ind_rate in xrange(len(X_IDX)): for ind_strength in xrange(len(Y_IDX)): tmp_mps = IDX[to1d(ind_rate, ind_strength, len(X_IDX))][2] Z_IDX[0][ind_rate][ind_strength] = tmp_mps[0] Z_IDX[1][ind_rate][ind_strength] = tmp_mps[1] Z_IDX[2][ind_rate][ind_strength] = tmp_mps['whole'] tmp_sts = IDX[to1d(ind_rate, ind_strength, len(X_IDX))][3] Z_IDX[3][ind_rate][ind_strength] = tmp_sts[0] Z_IDX[4][ind_rate][ind_strength] = tmp_sts[1] Z_IDX[5][ind_rate][ind_strength] = tmp_sts['whole'] # MPS plotting MPS_FIG, MPS_AXS = plt.subplots(1, 3, figsize=(9, 3)) MPS_MIN_MAX = get_all_min_max([Z_IDX[i] for i in xrange(3)]) MPS_NORM = colors.normalize(MPS_MIN_MAX[0], MPS_MIN_MAX[1]) plot_run(MPS_FIG, "MPS", MPS_AXS, Z_IDX, range(3), MPS_NORM, IMSHOW_EXTENT) # STS plotting STS_FIG, STS_AXS = plt.subplots(1, 3, figsize=(9, 3)) STS_MIN_MAX = get_all_min_max([Z_IDX[i] for i in xrange(3, 6)]) STS_NORM = colors.normalize(STS_MIN_MAX[0], STS_MIN_MAX[1]) plot_run(STS_FIG, "STS", STS_AXS, Z_IDX, range(3, 6), STS_NORM, IMSHOW_EXTENT) """ FFT MAX """ FFT_ATTRS = (('paramset', '_v_attrs', 'Common', 'inter_conn_rate', 0, 1), ('paramset', '_v_attrs', 'Common', 'inter_conn_strength', 0, 1),
def draw_3d_bar_chart(samples, top_level_names=None, second_level_names=None, title=None, xlabel=None, ylabel=None, zlabel=None, flip_y=True, third_level_names=None): # So, samples can either contain a list of lists. The top level list # contains top level groups, and the second level list contains actual # samples (top_level_grouping_only = true) # Alternatively, samples may be a list of lists of lists, with top-level # groups, second level groups and actual samples. (top_level_grouping_only) means = [] confs = [] second_level_grouping_available = \ isinstance(samples[0][0], collections.Sequence) top_level_methods = len(samples) if second_level_grouping_available: second_level_methods = len(samples[0]) samples2 = samples else: # Create artificial second level grouping second_level_methods = 1 samples2 = [[samples[i]] for i in range(top_level_methods)] for i in range(top_level_methods): means.append([]) confs.append([]) for i in range(top_level_methods): for j in range(second_level_methods): m, h = calculate_mean_and_standard_error(samples[i][j]) means[i].append(m) confs[i].append(h) ind = np.arange(second_level_methods) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') rects = [] xpos = np.array([]) ypos = np.array([]) zpos = np.array([]) dx = np.array([]) dy = np.array([]) dz = np.array([]) for j in range(second_level_methods): for i in range(top_level_methods): xpos = np.append(xpos, i) if flip_y: ypos = np.append(ypos, second_level_methods - j - 1) else: ypos = np.append(ypos, j) zpos = np.append(zpos, 0) dx = np.append(dx, 1.0) dy = np.append(dy, 0.5) dz = np.append(dz, means[i][j]) #http://stackoverflow.com/questions/11950375/apply-color-map-to-mpl-toolkits-mplot3d-axes3d-bar3d offset = dz + np.abs(dz.min()) fracs = offset.astype(float)/offset.max() norm = colors.normalize(fracs.min(), fracs.max()) colors_t = cm.jet(norm(fracs) / 2 + 0.5) # for xs, ys, zs, dxs, dys, dzs, colors_ts in zip(xpos, ypos, zpos, dx, dy, dz, colors_t): # rects.append(ax.bar3d(xs, ys, zs, dxs, dys, dzs, color=colors_ts, zsort='')) rects = ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors_t, zsort=True) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) if zlabel: ax.set_zlabel(zlabel) if title: ax.set_title(title) if second_level_grouping_available: ax.set_yticks(ind + 0.5) if second_level_names: if flip_y: second_level_names.reverse() ax.set_yticklabels(second_level_names) if third_level_names: ax.set_zticklabels(third_level_names) tick_multiplier = int(math.ceil(float(top_level_methods)/float(len(top_level_names)))) ax.set_xticks(tick_multiplier * np.arange(len(top_level_names)) + 0.5) xtickrotation = raw_input("Specify rotation for xticklabels [hit enter to use zero]: ") if xtickrotation is not None and xtickrotation != "": xtickrotation = float(xtickrotation) else: xtickrotation = 0.0 if top_level_names: ax.set_xticklabels(top_level_names, rotation=xtickrotation) # ax.legend(rects, top_level_names, mode='expand', ncol=3) return fig, ax, rects, means