我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.colors()。
def plot_by_training_samples(I_XT_array, I_TY_array, axes, epochsInds, f, index_i, index_j, size_ind, font_size, y_ticks, x_ticks, colorbar_axis, title_str, axis_font, bar_font, save_name, samples_labels): """Print the final epoch of all the diffrenet training samples size """ max_index = size_ind if size_ind!=-1 else I_XT_array.shape[2]-1 cmap = plt.get_cmap('gnuplot') colors = [cmap(i) for i in np.linspace(0, 1, max_index+1)] #Print the final epoch nums_epoch= -1 #Go over all the samples size and plot them with the right color for index_in_range in range(0, max_index): XT, TY = [], [] for layer_index in range(0, I_XT_array.shape[4]): XT.append(np.mean(I_XT_array[:, -1, index_in_range, nums_epoch, layer_index], axis=0)) TY.append(np.mean(I_TY_array[:, -1, index_in_range,nums_epoch, layer_index], axis=0)) axes[index_i, index_j].plot(XT, TY, marker='o', linestyle='-', markersize=12, markeredgewidth=0.2, linewidth=0.5, color=colors[index_in_range]) utils.adjustAxes(axes[index_i, index_j], axis_font=axis_font, title_str=title_str, x_ticks=x_ticks, y_ticks=y_ticks, x_lim=None, y_lim=None, set_xlabel=index_i == axes.shape[0] - 1, set_ylabel=index_j == 0, x_label='$I(X;T)$', y_label='$I(T;Y)$', set_xlim=True, set_ylim=True, set_ticks=True, label_size=font_size) #Create color bar and save it if index_i == axes.shape[0] - 1 and index_j == axes.shape[1] - 1: utils.create_color_bar(f, cmap, colorbar_axis, bar_font, epochsInds, title='Training Data') f.savefig(save_name + '.jpg', dpi=150, format='jpg')
def update_line_each_neuron(num, print_loss, Ix, axes, Iy, train_data, accuracy_test, epochs_bins, loss_train_data, loss_test_data, colors, epochsInds, font_size = 18, axis_font = 16, x_lim = [0,12.2], y_lim=[0, 1.08],x_ticks = [], y_ticks = []): """Update the figure of the infomration plane for the movie""" #Print the line between the points axes[0].clear() if len(axes)>1: axes[1].clear() #Print the points for layer_num in range(Ix.shape[2]): for net_ind in range(Ix.shape[0]): axes[0].scatter(Ix[net_ind,num, layer_num], Iy[net_ind,num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85) title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num]) utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='$I(X;T)$', y_label='$I(T;Y)$') #Print the loss function and the error if len(axes)>1: axes[1].plot(epochsInds[:num], 1 - np.mean(accuracy_test[:, :num], axis=0), color='g') if print_loss: axes[1].plot(epochsInds[:num], np.mean(loss_test_data[:, :num], axis=0), color='y') nereast_val = np.searchsorted(epochs_bins, epochsInds[num], side='right') axes[1].set_xlim([0,epochs_bins[nereast_val]]) axes[1].legend(('Accuracy', 'Loss Function'), loc='best')
def plot_hist(str_name, save_name='dist'): data_array = utils.get_data(str_name) params = np.squeeze(np.array(data_array['information'])) ind_array = data_array['params']['epochsInds'] DKL_YgX_YgT = utils.extract_array(params, 'DKL_YgX_YgT') p_ts = utils.extract_array(params, 'pts') H_Xgt = utils.extract_array(params, 'H_Xgt') f, (axes) = plt.subplots(3, 1) #axes = [axes] f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS line_ani = animation.FuncAnimation(f, update_bars_num_of_ts, len(p_ts), repeat=False, interval=1, blit=False, fargs=[p_ts,H_Xgt,DKL_YgX_YgT, axes,ind_array]) Writer = animation.writers['ffmpeg'] writer = Writer(fps=50) #Save the movie line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250) plt.show()
def plot_RF(rf, sample_shape): norm = matplotlib.colors.Normalize() norm.autoscale(rf) rf = np.resize(rf, np.prod(sample_shape)).reshape(sample_shape) norm_zero = min(max(norm(0.0), 0.0+1e-6), 1.0-1e-6) cdict = { 'red' : ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.)), 'green': ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.)), 'blue' : ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.)) } #generate the colormap with 1024 interpolated values my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 1024) plt.imshow(rf, interpolation='nearest', origin='upper', cmap=my_cmap) ax = plt.gca() ax.xaxis.set_visible(False) ax.yaxis.set_visible(False)
def get_stock_signal_data(): fname = os.path.join(os.getcwd(), 'data', 'stock_data', '_IF000.csv') price_data = csv2frame(fname) from matplotlib.colors import colorConverter info = load_tradeinfo("_djtrend2_IF000") entry_x = [] entry_y = info['entry_price'].tolist() exit_x = [] exit_y = info['exit_price'].tolist() colors = [] for t in info.index: entry_x.append(price_data.index.searchsorted(t)) for t in info['exit_datetime'].values: exit_x.append(price_data.index.searchsorted(t)) for i in range(len(info)): tr = info.ix[i] if tr['islong']: c = 'r' if tr['exit_price']>tr['entry_price'] else 'w' else: c = 'r' if tr['exit_price']<tr['entry_price'] else 'w' r,g,b = colorConverter.to_rgb(c) colors.append((r,g,b,1)) return price_data, entry_x, entry_y, exit_x, exit_y, colors
def _cmap_discretize(cmap, N): """Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ if type(cmap) == str: cmap = plt.get_cmap(cmap) colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.))) colors_rgba = cmap(colors_i) indices = np.linspace(0, 1., N+1) cdict = {} for ki, key in enumerate(('red','green','blue')): cdict[key] = [(indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1)] # Return colormap object. return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
def _apply_style_colors(self, colors, kwds, col_num, label): """ Manage style and color based on column number and its label. Returns tuple of appropriate style and kwds which "color" may be added. """ style = None if self.style is not None: if isinstance(self.style, list): try: style = self.style[col_num] except IndexError: pass elif isinstance(self.style, dict): style = self.style.get(label, style) else: style = self.style has_color = 'color' in kwds or self.colormap is not None nocolor_style = style is None or re.match('[a-z]+', style) is None if (has_color or self.subplots) and nocolor_style: kwds['color'] = colors[col_num % len(colors)] return style, kwds
def _make_plot(self): colors = self._get_colors() stacking_id = self._get_stacking_id() for i, (label, y) in enumerate(self._iter_data()): ax = self._get_ax(i) kwds = self.kwds.copy() label = com.pprint_thing(label) kwds['label'] = label style, kwds = self._apply_style_colors(colors, kwds, i, label) if style is not None: kwds['style'] = style kwds = self._make_plot_keywords(kwds, y) artists = self._plot(ax, y, column_num=i, stacking_id=stacking_id, **kwds) self._add_legend_handle(artists[0], label, index=i)
def maybe_color_bp(self, bp): if isinstance(self.color, dict): boxes = self.color.get('boxes', self._boxes_c) whiskers = self.color.get('whiskers', self._whiskers_c) medians = self.color.get('medians', self._medians_c) caps = self.color.get('caps', self._caps_c) else: # Other types are forwarded to matplotlib # If None, use default colors boxes = self.color or self._boxes_c whiskers = self.color or self._whiskers_c medians = self.color or self._medians_c caps = self.color or self._caps_c from matplotlib.artist import setp setp(bp['boxes'], color=boxes, alpha=1) setp(bp['whiskers'], color=whiskers, alpha=1) setp(bp['medians'], color=medians, alpha=1) setp(bp['caps'], color=caps, alpha=1)
def _get_fill_and_line_colors(self, min_n, max_n): colors = self._get_colors_for_boardings(min_n, max_n) n_boardings_range = range(min_n, max_n + 1) nboardings_to_color = {n: colors[i] for i, n in enumerate(n_boardings_range)} n_boardings_to_line_color = {} n_boardings_to_fill_color = {} # rgbs = [color_tuple[:3] for color_tuple in nboardings_to_color.values()] hsvs = matplotlib.colors.rgb_to_hsv(rgbs) max_saturation = max([hsv[1] for hsv in hsvs]) line_saturation_multiplier = 1 / max_saturation for n, color_tuple in nboardings_to_color.items(): c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_saturation(color_tuple, line_saturation_multiplier) c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_brightness(c, 1) n_boardings_to_line_color[n] = c c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_brightness(color_tuple, 1.2) c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_saturation(c, 0.8) n_boardings_to_fill_color[n] = c return n_boardings_to_fill_color, n_boardings_to_line_color
def __init__(self, vmax=None, clip=False): """ If *vmax* is not given, it is initialized from the maximum absolute value of the first input processed. That is, *__call__(A)* calls *autoscale_None(A)*. If *clip* is *True* and the given value falls outside the range, the returned value will be 0 or 1, whichever is closer. Works with scalars or arrays, including masked arrays. If *clip* is *True*, masked values are set to 1; otherwise they remain masked. Clipping silently defeats the purpose of setting the over, under, and masked colors in the colormap, so it is likely to lead to surprises; therefore the default is *clip* = *False*. """ self.vmax = vmax self.clip = clip
def dismph_colormap(): '''Make a custom colormap like the one used in dismph. The list was created from dismphN.mat in geodmod which is a 64 segmented colormap using the following: from scipy.io import loadmat cmap = loadmat('dismphN.mat',struct_as_record=True)['dismphN'] from matplotlib.colors import rgb2hex list=[] for i in cmap: list.append(rgb2hex(i)) ''' list = ['#f579cd', '#f67fc6', '#f686bf', '#f68cb9', '#f692b3', '#f698ad', '#f69ea7', '#f6a5a1', '#f6ab9a', '#f6b194', '#f6b78e', '#f6bd88', '#f6c482', '#f6ca7b', '#f6d075', '#f6d66f', '#f6dc69', '#f6e363', '#efe765', '#e5eb6b', '#dbf071', '#d0f477', '#c8f67d', '#c2f684', '#bbf68a', '#b5f690', '#aff696', '#a9f69c', '#a3f6a3', '#9cf6a9', '#96f6af', '#90f6b5', '#8af6bb', '#84f6c2', '#7df6c8', '#77f6ce', '#71f6d4', '#6bf6da', '#65f6e0', '#5ef6e7', '#58f0ed', '#52e8f3', '#4cdbf9', '#7bccf6', '#82c4f6', '#88bdf6', '#8eb7f6', '#94b1f6', '#9aabf6', '#a1a5f6', '#a79ef6', '#ad98f6', '#b392f6', '#b98cf6', '#bf86f6', '#c67ff6', '#cc79f6', '#d273f6', '#d86df6', '#de67f6', '#e561f6', '#e967ec', '#ed6de2', '#f173d7'] dismphCM = matplotlib.colors.LinearSegmentedColormap.from_list('mycm', list) dismphCM.set_bad('w', 0.0) return dismphCM
def get_cmap(N): color_norm = colors.Normalize(vmin=0, vmax=N-1) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') def map_index_to_rgb_color(index): return scalar_map.to_rgba(index) return map_index_to_rgb_color
def plotImage(self, I, ax=None, showIt=False, grid=False, clim=None): if self.dim == 3: raise Exception('Use plot slice?') import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.mplot3d import Axes3D import matplotlib.colors as colors import matplotlib.cm as cmx if ax is None: ax = plt.subplot(111) jet = cm = plt.get_cmap('jet') cNorm = colors.Normalize( vmin=I.min() if clim is None else clim[0], vmax=I.max() if clim is None else clim[1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) ax.set_xlim((self.x0[0], self.h[0].sum())) ax.set_ylim((self.x0[1], self.h[1].sum())) for ii, node in enumerate(self._sortedCells): x0, sz = self._cellN(node), self._cellH(node) ax.add_patch(plt.Rectangle((x0[0], x0[1]), sz[0], sz[1], facecolor=scalarMap.to_rgba(I[ii]), edgecolor='k' if grid else 'none')) # if text: ax.text(self.center[0],self.center[1],self.num) scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots ax.set_xlabel('x') ax.set_ylabel('y') if showIt: plt.show() return [scalarMap]
def plotImage( self, I, ax=None, showIt=False, grid=False, clim=None ): if self.dim == 3: raise NotImplementedError('This is not yet done!') import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.mplot3d import Axes3D import matplotlib.colors as colors import matplotlib.cm as cmx if ax is None: ax = plt.subplot(111) jet = cm = plt.get_cmap('jet') cNorm = colors.Normalize( vmin=I.min() if clim is None else clim[0], vmax=I.max() if clim is None else clim[1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) # ax.set_xlim((self.x0[0], self.h[0].sum())) # ax.set_ylim((self.x0[1], self.h[1].sum())) Nx = self.r(self.gridN[:, 0], 'N', 'N', 'M') Ny = self.r(self.gridN[:, 1], 'N', 'N', 'M') cell = self.r(I, 'CC', 'CC', 'M') for ii in range(self.nCx): for jj in range(self.nCy): I = [ii, ii+1, ii+1, ii] J = [jj, jj, jj+1, jj+1] ax.add_patch(plt.Polygon(np.c_[Nx[I, J], Ny[I, J]], facecolor=scalarMap.to_rgba(cell[ii, jj]), edgecolor='k' if grid else 'none')) scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots ax.set_xlabel('x') ax.set_ylabel('y') if showIt: plt.show() return [scalarMap]
def compute_venn2_colors(set_colors): ''' Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 3 elements, providing colors for regions (10, 01, 11). >>> compute_venn2_colors(('r', 'g')) (array([ 1., 0., 0.]), array([ 0. , 0.5, 0. ]), array([ 0.7 , 0.35, 0. ])) ''' ccv = ColorConverter() base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors] return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]))
def update_line_specipic_points(nums, data, axes, to_do, font_size, axis_font): """Update the lines in the axes for snapshot of the whole process""" colors =LAYERS_COLORS x_ticks = [0, 2, 4, 6, 8, 10] #Go over all the snapshot for i in range(len(nums)): num = nums[i] #Plot the right layer for layer_num in range(data.shape[3]): axes[i].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 105,edgecolors = 'black',alpha = 0.85) utils.adjustAxes(axes[i], axis_font=axis_font, title_str='', x_ticks=x_ticks, y_ticks=[], x_lim=None, y_lim=None, set_xlabel=to_do[i][0], set_ylabel=to_do[i][1], x_label='$I(X;T)$', y_label='$I(T;Y)$', set_xlim=True, set_ylim=True, set_ticks=True, label_size=font_size)
def update_line(num, print_loss, data, axes, epochsInds, test_error, test_data, epochs_bins, loss_train_data, loss_test_data, colors, font_size = 18, axis_font=16, x_lim = [0,12.2], y_lim=[0, 1.08], x_ticks = [], y_ticks = []): """Update the figure of the infomration plane for the movie""" #Print the line between the points cmap = ListedColormap(LAYERS_COLORS) segs = [] for i in range(0, data.shape[1]): x = data[0, i, num, :] y = data[1, i, num, :] points = np.array([x, y]).T.reshape(-1, 1, 2) segs.append(np.concatenate([points[:-1], points[1:]], axis=1)) segs = np.array(segs).reshape(-1, 2, 2) axes[0].clear() if len(axes)>1: axes[1].clear() lc = LineCollection(segs, cmap=cmap, linestyles='solid',linewidths = 0.3, alpha = 0.6) lc.set_array(np.arange(0,5)) #Print the points for layer_num in range(data.shape[3]): axes[0].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85) axes[1].plot(epochsInds[:num], 1 - np.mean(test_error[:, :num], axis=0), color ='r') title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num]) utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='$I(X;T)$', y_label='$I(T;Y)$') title_str = 'Precision as function of the epochs' utils.adjustAxes(axes[1], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='# Epochs', y_label='Precision')
def plot_animation_each_neuron(name_s, save_name, print_loss=False): """Plot the movie for all the networks in the information plane""" # If we want to print the loss function also #The bins that we extened the x axis of the accuracy each time epochs_bins = [0, 500, 1500, 3000, 6000, 10000, 20000] data_array = utils.get_data(name_s[0][0]) data = np.squeeze(data_array['information']) f, (axes) = plt.subplots(1, 1) axes = [axes] f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS #new/old version Ix = np.squeeze(data[0,:, :, :]) Iy = np.squeeze(data[1,:, :, :]) #Interploation of the samplings (because we don't cauclaute the infomration in each epoch) #interp_data_x = interp1d(epochsInds, Ix, axis=1) #interp_data_y = interp1d(epochsInds, Iy, axis=1) #new_x = np.arange(0,epochsInds[-1]) #new_data = np.array([interp_data_x(new_x), interp_data_y(new_x)]) """" train_data = interp1d(epochsInds, np.squeeze(train_data), axis=1)(new_x) test_data = interp1d(epochsInds, np.squeeze(test_data), axis=1)(new_x) if print_loss: loss_train_data = interp1d(epochsInds, np.squeeze(loss_train_data), axis=1)(new_x) loss_test_data=interp1d(epochsInds, np.squeeze(loss_test_data), axis=1)(new_x) """ line_ani = animation.FuncAnimation(f, update_line_each_neuron, Ix.shape[1], repeat=False, interval=1, blit=False, fargs=(print_loss, Ix, axes,Iy,train_data,test_data,epochs_bins, loss_train_data,loss_test_data, colors,epochsInds)) Writer = animation.writers['ffmpeg'] writer = Writer(fps=100) #Save the movie line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250) plt.show()
def rgb_to_hsv(rgb_list): rgb_normalized = [1.0*rgb_list[0]/255, 1.0*rgb_list[1]/255, 1.0*rgb_list[2]/255] hsv_normalized = matplotlib.colors.rgb_to_hsv([[rgb_normalized]])[0][0] return hsv_normalized
def compute_color_histograms(cloud, using_hsv=False): numBins = 64 # Compute histograms for the clusters point_colors_list = [] # Step through each point in the point cloud for point in pc2.read_points(cloud, skip_nans=True): rgb_list = float_to_rgb(point[3]) if using_hsv: point_colors_list.append(rgb_to_hsv(rgb_list) * 255) else: point_colors_list.append(rgb_list) # Populate lists with color values channel_1_vals = [] channel_2_vals = [] channel_3_vals = [] for color in point_colors_list: channel_1_vals.append(color[0]) channel_2_vals.append(color[1]) channel_3_vals.append(color[2]) # Compute histograms for the colors in the point cloud channel1_hist = np.histogram(channel_1_vals, bins=numBins, range=(0, 256)) channel2_hist = np.histogram(channel_2_vals, bins=numBins, range=(0, 256)) channel3_hist = np.histogram(channel_3_vals, bins=numBins, range=(0, 256)) # Concatenate and normalize the histograms hist_features = np.concatenate((channel1_hist[0],channel2_hist[0], channel3_hist[0])).astype(np.float64) normed_features = hist_features / np.sum(hist_features) return normed_features
def main(): # Demo of how to reduce the dimensionality of the data to two dimension # and plot the results. # Load the dataset data = datasets.load_digits() X = data.data y = data.target # Project the data onto the 2 primary principal components X_trans = PCA().transform(X, 2) x1 = X_trans[:, 0] x2 = X_trans[:, 1] cmap = plt.get_cmap('viridis') colors = [cmap(i) for i in np.linspace(0, 1, len(np.unique(y)))] class_distr = [] # Plot the different class distributions for i, l in enumerate(np.unique(y)): _x1 = x1[y == l] _x2 = x2[y == l] _y = y[y == l] class_distr.append(plt.scatter(_x1, _x2, color=colors[i])) # Add a legend plt.legend(class_distr, y, loc=1) # Axis labels plt.suptitle("PCA Dimensionality Reduction") plt.title("Digit Dataset") plt.xlabel('Principal Component 1') plt.ylabel('Principal Component 2') plt.show()
def plot_in_2d(self, X, y=None, title=None, accuracy=None, legend_labels=None): X_transformed = self._transform(X, dim=2) x1 = X_transformed[:, 0] x2 = X_transformed[:, 1] class_distr = [] y = np.array(y).astype(int) colors = [self.cmap(i) for i in np.linspace(0, 1, len(np.unique(y)))] # Plot the different class distributions for i, l in enumerate(np.unique(y)): _x1 = x1[y == l] _x2 = x2[y == l] _y = y[y == l] class_distr.append(plt.scatter(_x1, _x2, color=colors[i])) # Plot legend if not legend_labels is None: plt.legend(class_distr, legend_labels, loc=1) # Plot title if title: if accuracy: perc = 100 * accuracy plt.suptitle(title) plt.title("Accuracy: %.1f%%" % perc, fontsize=10) else: plt.title(title) # Axis labels plt.xlabel('Principal Component 1') plt.ylabel('Principal Component 2') plt.show() # Plot the dataset X and the corresponding labels y in 3D using PCA.
def bar3d(h2, ax, **kwargs): """Plot of 2D histograms as 3D boxes. Parameters ---------- h2 : Histogram2D Returns ------- plt.Axes """ density = kwargs.pop("density", False) data = get_data(h2, cumulative=False, flatten=True, density=density) # transformed = transform_data(data, kwargs) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) else: colors = kwargs.pop("color", "blue") xpos, ypos = (arr.flatten() for arr in h2.get_bin_centers()) zpos = np.zeros_like(ypos) dx, dy = (arr.flatten() for arr in h2.get_bin_widths()) _add_labels(ax, h2, kwargs) ax.bar3d(xpos, ypos, zpos, dx, dy, data, color=colors, **kwargs) ax.set_zlabel("density" if density else "frequency") return ax
def polar_map(hist, ax, show_zero=True, **kwargs): """Polar map of polar histograms. Similar to map, but supports less parameters. Returns ------- plt.Axes """ data = get_data(hist, cumulative=False, flatten=True, density=kwargs.pop("density", False)) # transformed = transform_data(data, kwargs) cmap = _get_cmap(kwargs) norm, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) rpos, phipos = (arr.flatten() for arr in hist.get_bin_left_edges()) dr, dphi = (arr.flatten() for arr in hist.get_bin_widths()) rmax, _ = (arr.flatten() for arr in hist.get_bin_right_edges()) bar_args = {} if "zorder" in kwargs: bar_args["zorder"] = kwargs.pop("zorder") alphas = _get_alpha_data(cmap_data, kwargs) if np.isscalar(alphas): alphas = np.ones_like(data) * alphas for i in range(len(rpos)): if data[i] > 0 or show_zero: bin_color = colors[i] # TODO: align = "edge" bars = ax.bar(phipos[i], dr[i], width=dphi[i], bottom=rpos[i], color=bin_color, edgecolor=kwargs.get("grid_color", cmap(0.5)), lw=kwargs.get("lw", 0.5), alpha=alphas[i], **bar_args) ax.set_rmax(rmax.max()) return ax
def _get_cmap_data(data, kwargs): """Get normalized values to be used with a colormap. Parameters ---------- data : array_like cmap_min : Optional[float] or "min" By default 0. If "min", minimum value of the data. cmap_max : Optional[float] By default, maximum value of the data cmap_normalize : str or colors.Normalize Returns ------- normalizer : colors.Normalize normalized_data : array_like """ norm = kwargs.pop("cmap_normalize", None) if norm == "log": cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", data[data > 0].min()) norm = colors.LogNorm(cmap_min, cmap_max) elif not norm: cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", 0) if cmap_min == "min": cmap_min = data.min() norm = colors.Normalize(cmap_min, cmap_max, clip=True) return norm, norm(data)
def _add_colorbar(ax, cmap, cmap_data, norm): """Show a colorbar right of the plot. Parameters ---------- ax : plt.Axes cmap : colors.Colormap cmap_data : array_like norm : colors.Normalize """ fig = ax.get_figure() mappable = cm.ScalarMappable(cmap=cmap, norm=norm) mappable.set_array(cmap_data) # TODO: Or what??? fig.colorbar(mappable, ax=ax)
def __init__(self, line_width=0.002, alpha = 1.0, color='black'): from matplotlib.colors import ColorConverter conv = ColorConverter() PlotCallback.__init__(self) self.line_width = line_width self.alpha = alpha self.color = (np.array(conv.to_rgb(color)) * 255).astype("uint8")
def get_cmap(N): '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.''' color_norm = colors.Normalize(vmin=0, vmax=N-1) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') def map_index_to_rgb_color(index): return scalar_map.to_rgba(index) return map_index_to_rgb_color
def scatter_classes(x, classes, ax=None): """Scatter the data points coloring by the classes.""" if ax is None: _fig, ax = plt.subplots() ax = plt.gca() if ax is None else ax cmap = matplotlib.cm.jet norm = matplotlib.colors.Normalize( vmin=np.min(classes), vmax=np.max(classes)) mapper = matplotlib.cm.ScalarMappable(cmap=cmap, norm=norm) colors = mapper.to_rgba(classes) ax.scatter(x[:,0], x[:,1], color=colors) return ax
def surface_plot(figure,X,Y,Z,color1,color2=None,xlabel="",ylabel="",zlabel="",alpha=1.0,linewidth=3,label=""): from mpl_toolkits.mplot3d import axes3d from matplotlib.colors import LinearSegmentedColormap if color2 is None: color2 = color1 cdict = {'red': ((0.0, color1[0], color1[0]),(1.0, color2[0], color2[0])), 'green': ((0.0, color1[1], color1[1]),(1.0, color2[1], color2[1])), 'blue': ((0.0, color1[2], color1[2]),(1.0, color2[2], color2[2]))} cmap = LinearSegmentedColormap('CMap', cdict) font = fm.FontProperties(family = 'Trebuchet', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111,projection='3d') if X.ndim<2: X = np.tile(np.array(X),(Y.shape[-1],1)).transpose() if Y.ndim<2: Y = np.tile(np.array(Y),(X.shape[0],1)) axes.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cmap,alpha=alpha,linewidth=linewidth,label=label) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xlim(X.min(),X.max()) axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_ylim(Y.min(),Y.max()) axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12) axes.set_zlabel(zlabel, fontproperties=font, size=10, style='italic') axes.set_zlim(Z.min(),Z.max()) axes.set_zticklabels(axes.get_zticks(),fontproperties=font, size=12)
def density_plot(figure,X,Y,color,xlabel="",ylabel="",n_points=10,linewidth=1,marker_size=40.,alpha=1.0,label=""): font = fm.FontProperties(family = 'Trebuchet', weight ='light') #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111) # axes.plot(X,Y,linewidth=1,color=tuple(color2),alpha=0.2) # ratios = (Y-Y.min())/(Y.max()-Y.min()) # X_min = X.mean()-3*X.std() # X_max = X.mean()+3*X.std() X_min = np.percentile(X,100/n_points) X_max = np.percentile(X,100 - 100/n_points) Y_min = np.percentile(Y,100/n_points) # Y_min = Y.mean()-3*Y.std() Y_max = np.percentile(Y,100 - 100/n_points) X_grid = np.linspace(X_min,X_max,n_points) Y_grid = np.linspace(Y_min,Y_max,n_points) X_sampled = X_grid[vq(X,X_grid)[0]] Y_sampled = Y_grid[vq(Y,Y_grid)[0]] point_density = {} for x in np.unique(X_sampled): point_count = nd.sum(np.ones_like(np.where(X_sampled==x)),Y_sampled[np.where(X_sampled==x)],index=np.unique(Y_sampled)) for i,y in enumerate(np.unique(Y_sampled)): point_density[(x,y)] = point_count[i]/len(Y) point_area = np.array([np.pi*10.0*marker_size*point_density[(x,y)]/np.array(point_density.values()).max() for x,y in zip(X_sampled,Y_sampled)]) #colors = np.random.rand(len(X)) colors = np.array([point_density[(x,y)]/np.array(point_density.values()).max() * color for x,y in zip(X_sampled,Y_sampled)]) colors += np.array([(1-point_density[(x,y)]/np.array(point_density.values()).max()) * np.ones(3) for x,y in zip(X_sampled,Y_sampled)]) axes.scatter(X_sampled,Y_sampled,s=point_area,c=colors,linewidth=linewidth,alpha=alpha,label=label) axes.set_xlim(X_min,X_max) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) axes.set_ylim(Y_min,Y_max) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def violin_plot(figure,X,data,colors,xlabel="",ylabel="",n_points=400,violin_width=None,linewidth=3,marker_size=20): font = fm.FontProperties(family = 'Trebuchet', weight ='light') #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111) if violin_width is None: if len(X)>1: violin_width = ((np.array(X)[1:] - np.array(X)[:-1]).mean())/3. else: violin_width = 0.33 for x in xrange(len(X)): color = colors[x] Y = gaussian_kde(data[x]) D_smooth = np.linspace(np.percentile(Y.dataset,1),np.percentile(Y.dataset,99),n_points) Y_smooth = Y.evaluate(D_smooth) Y_smooth = violin_width*Y_smooth/Y_smooth.max() axes.fill_betweenx(D_smooth,X[x],X[x]+Y_smooth,facecolor=color,alpha=0.1) axes.fill_betweenx(D_smooth,X[x],X[x]-Y_smooth,facecolor=color,alpha=0.1) axes.plot(X[x]+Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8) axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8) axes.plot([X[x]-Y_smooth[0],X[x]+Y_smooth[0]],[D_smooth[0],D_smooth[0]],color=color,linewidth=linewidth,alpha=0.8) axes.plot([X[x]-Y_smooth[-1],X[x]+Y_smooth[-1]],[D_smooth[-1],D_smooth[-1]],color=color,linewidth=linewidth,alpha=0.8) axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8) axes.plot(X[x],np.percentile(data[x],50),'o',markersize=marker_size,markeredgewidth=linewidth,color=color) axes.plot([X[x],X[x]],[np.percentile(data[x],25),np.percentile(data[x],75)],color=color,linewidth=2*linewidth,alpha=0.5) axes.set_xlim(min(X)-1,max(X)+1) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def _animate(fig, ax, frame_data, line_width=2, fps=10, tail_color='r', tail_alpha=0.75, head_color='b', head_alpha=1): segments, segment_frames, timestamps, fade_frames = frame_data head_color = np.array(to_rgb(head_color))[None] tail_color = np.array(to_rgb(tail_color))[None] # start with all segments transparent segment_colors = np.zeros((len(segments), 4), dtype=float) lines = LineCollection(segments, linewidths=line_width, colors=segment_colors) ax.add_collection(lines) timer = ax.text(1, 0, '0:00:00', transform=ax.transAxes, zorder=3, verticalalignment='bottom', horizontalalignment='right', bbox=dict(facecolor='white')) def update_frame(frame_idx): frame_diff = frame_idx - segment_frames mask = frame_diff < 0 # compute head alpha alpha1 = 1 - np.minimum(frame_diff/fade_frames, 1) alpha1[mask] = 0 alpha1 *= head_alpha # compute tail alpha alpha2 = (1 - mask) * tail_alpha # composite alpha and colors color, alpha = _blend_alpha(head_color, alpha1, tail_color, alpha2) segment_colors[:, :3] = color segment_colors[:, 3] = alpha lines.set_color(segment_colors) timer.set_text(timestamps[frame_idx]) return lines, timer interval = 1000. / fps return FuncAnimation(fig, update_frame, frames=len(timestamps), blit=True, interval=interval, repeat=True)
def _validate_color_args(self): if 'color' not in self.kwds and 'colors' in self.kwds: warnings.warn(("'colors' is being deprecated. Please use 'color'" "instead of 'colors'")) colors = self.kwds.pop('colors') self.kwds['color'] = colors if ('color' in self.kwds and self.nseries == 1): # support series.plot(color='green') self.kwds['color'] = [self.kwds['color']] if ('color' in self.kwds or 'colors' in self.kwds) and \ self.colormap is not None: warnings.warn("'color' and 'colormap' cannot be used " "simultaneously. Using 'color'") if 'color' in self.kwds and self.style is not None: if com.is_list_like(self.style): styles = self.style else: styles = [self.style] # need only a single match for s in styles: if re.match('^[a-z]+?', s) is not None: raise ValueError( "Cannot pass 'style' string with a color " "symbol and 'color' keyword argument. Please" " use one or the other or pass 'style' " "without a color symbol")
def _make_plot(self): if self._is_ts_plot(): from pandas.tseries.plotting import _maybe_convert_index data = _maybe_convert_index(self._get_ax(0), self.data) x = data.index # dummy, not used plotf = self._ts_plot it = self._iter_data(data=data, keep_index=True) else: x = self._get_xticks(convert_period=True) plotf = self._plot it = self._iter_data() stacking_id = self._get_stacking_id() is_errorbar = any(e is not None for e in self.errors.values()) colors = self._get_colors() for i, (label, y) in enumerate(it): ax = self._get_ax(i) kwds = self.kwds.copy() style, kwds = self._apply_style_colors(colors, kwds, i, label) errors = self._get_errorbars(label=label, index=i) kwds = dict(kwds, **errors) label = com.pprint_thing(label) # .encode('utf-8') kwds['label'] = label newlines = plotf(ax, x, y, style=style, column_num=i, stacking_id=stacking_id, is_errorbar=is_errorbar, **kwds) self._add_legend_handle(newlines[0], label, index=i) lines = _get_all_lines(ax) left, right = _get_xlim(lines) ax.set_xlim(left, right)
def _validate_color_args(self): if 'color' in self.kwds: if self.colormap is not None: warnings.warn("'color' and 'colormap' cannot be used " "simultaneously. Using 'color'") self.color = self.kwds.pop('color') if isinstance(self.color, dict): valid_keys = ['boxes', 'whiskers', 'medians', 'caps'] for key, values in compat.iteritems(self.color): if key not in valid_keys: raise ValueError("color dict contains invalid " "key '{0}' " "The key must be either {1}" .format(key, valid_keys)) else: self.color = None # get standard colors for default colors = _get_standard_colors(num_colors=3, colormap=self.colormap, color=None) # use 2 colors by default, for box/whisker and median # flier colors isn't needed here # because it can be specified by ``sym`` kw self._boxes_c = colors[0] self._whiskers_c = colors[0] self._medians_c = colors[2] self._caps_c = 'k' # mpl default
def __init__(self, gt, joints, dolegend=True, linewidth=1): """ Initialize class :type gt: groundtruth joints :type joints: calculated joints """ super(ICVLHandposeEvaluation, self).__init__(gt, joints, dolegend, linewidth) import matplotlib.colors # setup specific stuff self.jointNames = ['C', 'T1', 'T2', 'T3', 'I1', 'I2', 'I3', 'M1', 'M2', 'M3', 'R1', 'R2', 'R3', 'P1', 'P2', 'P3'] self.jointColors = [matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 0, 0.0]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 1.0]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 1.0]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 1.0]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 1.0]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 1.0]]]))[0, 0]] self.jointConnections = [[0, 1], [1, 2], [2, 3], [0, 4], [4, 5], [5, 6], [0, 7], [7, 8], [8, 9], [0, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15]] self.jointConnectionColors = [matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 1]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 1]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 1]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 1]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 1]]]))[0, 0]] self.plotMaxJointDist = 80 self.VTKviewport = [0, 0, 180, 40, 40] self.fps = 10.0
def _get_colors_for_boardings(cls, min_n_boardings, max_n_boardings): cmap = NodeProfileAnalyzerTimeAndVehLegs.get_colormap_for_boardings(max_n_boardings) colors = [cmap(float(n_boardings) / max_n_boardings) for n_boardings in range(int(max_n_boardings) + 1)] return colors[min_n_boardings:max_n_boardings + 1]
def _multiply_color_saturation(cls, color, multiplier): hsv = matplotlib.colors.rgb_to_hsv(color[:3]) rgb = matplotlib.colors.hsv_to_rgb((hsv[0], hsv[1] * multiplier, hsv[2])) return list(iter(rgb)) + [1]
def _multiply_color_brightness(cls, color, multiplier): hsv = matplotlib.colors.rgb_to_hsv(color[:3]) rgb = matplotlib.colors.hsv_to_rgb((hsv[0], hsv[1], max(0, min(1, hsv[2] * multiplier)))) return list(iter(rgb)) + [1]
def get_line_color(ix, modifier=None): colour = _lines_colour_cycle[ix] if modifier=='dark': return tuple(c/2 for c in colors.hex2color(colour)) elif modifier=='light': return tuple(1-(1-c)/2 for c in colors.hex2color(colour)) elif modifier is not None: raise NotImplementedError(modifier) return colors.hex2color(colour)
def set_cmap_synthetic(self, cmap): self._cmap = pylab.get_cmap(cmap) self._cNorm = colors.Normalize(vmin=0, vmax=self.nb_cells) self._scalarMap_synthetic = pylab.cm.ScalarMappable(norm=self._cNorm, cmap=self._cmap)
def set_cmap_circus(self, cmap): self._cmap = pylab.get_cmap(cmap) self._cNorm = colors.Normalize(vmin=0, vmax=self.nb_templates) self._scalarMap_circus = pylab.cm.ScalarMappable(norm=self._cNorm, cmap=self._cmap)
def diverge_map(low=(239/255., 65/255., 50/255.), high=(39/255., 184/255., 148/255.)): """Low and high are colors that will be used for the two ends of the spectrum. they can be either color strings or rgb color tuples """ c = mcolors.ColorConverter().to_rgb if isinstance(low, basestring): low = c(low) if isinstance(high, basestring): high = c(high) return make_colormap([low, c('white'), 0.5, c('white'), high])
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'): with warnings.catch_warnings(): warnings.filterwarnings("ignore") g = nx.from_numpy_matrix(am) if position is None: position=nx.drawing.circular_layout(g) fig = plt.figure() if cls is None: cls='r' else: # Make a user-defined colormap. cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"]) # Make a normalizer that will map the time values from # [start_time,end_time+1] -> [0,1]. cnorm = mcol.Normalize(vmin=0, vmax=1) # Turn these into an object that can be used to map time values to colors and # can be passed to plt.colorbar(). cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1) cpick.set_array([]) cls = cpick.to_rgba(cls) plt.colorbar(cpick, ax=fig.add_subplot(111)) nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111)) fig.savefig(os.path.join(self.plotdir, fig_name))
def _colorline(ax, x, y, color = (0, 0, 0), **kwargs): ''' Plots the curve `y(x)` with linearly increasing alpha. Adapted from `http://nbviewer.jupyter.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb`_. ''' # A bit hacky... But there doesn't seem to be # an easy way to get the hex code for a named color... if isinstance(color, string_types): if color.startswith("#"): hex = color[1:] else: if len(color) == 1: if color == 'k': color = 'black' elif color == 'r': color = 'red' elif color == 'b': color = 'blue' elif color == 'g': color = 'green' elif color == 'y': color = 'yellow' elif color == 'w': color = 'white' else: # ?! color = 'black' hex = matplotlib.colors.cnames[color.lower()][1:] r, g, b = tuple(int(hex[i:i+2], 16) / 255. for i in (0, 2, 4)) else: r, g, b = color colors = [(r, g, b, i) for i in np.linspace(0, 1, 3)] cmap = LinearSegmentedColormap.from_list('alphacmap', colors, N = 1000) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, array = np.linspace(0.0, 1.0, len(x)), cmap = cmap, norm = pl.Normalize(0.0, 1.0), **kwargs) ax.add_collection(lc) return lc
def plot_all_epochs(gen_data, I_XT_array, I_TY_array, axes, epochsInds, f, index_i, index_j, size_ind, font_size, y_ticks, x_ticks, colorbar_axis, title_str, axis_font, bar_font, save_name, plot_error = True,index_to_emphasis=1000): """Plot the infomration plane with the epochs in diffrnet colors """ #If we want to plot the train and test error if plot_error: fig_strs = ['train_error','test_error','loss_train','loss_test' ] fig_data = [np.squeeze(gen_data[fig_str]) for fig_str in fig_strs] f1 = plt.figure(figsize=(12, 8)) ax1 = f1.add_subplot(111) mean_sample = False if len(fig_data[0].shape)==1 else True if mean_sample: fig_data = [ np.mean(fig_data_s, axis=0) for fig_data_s in fig_data] for i in range(len(fig_data)): ax1.plot(epochsInds, fig_data[i],':', linewidth = 3 , label = fig_strs[i]) ax1.legend(loc='best') f = plt.figure(figsize=(12, 8)) axes = f.add_subplot(111) axes = np.array([[axes]]) I_XT_array = np.squeeze(I_XT_array) I_TY_array = np.squeeze(I_TY_array) if len(I_TY_array[0].shape) >1: I_XT_array = np.mean(I_XT_array, axis=0) I_TY_array = np.mean(I_TY_array, axis=0) max_index = size_ind if size_ind != -1 else I_XT_array.shape[0] cmap = plt.get_cmap('gnuplot') #For each epoch we have diffrenet color colors = [cmap(i) for i in np.linspace(0, 1, epochsInds[max_index-1]+1)] #Change this if we have more then one network arch nums_arc= -1 #Go over all the epochs and plot then with the right color for index_in_range in range(0, max_index): XT = I_XT_array[index_in_range, :] TY = I_TY_array[index_in_range, :] #If this is the index that we want to emphsis if epochsInds[index_in_range] ==index_to_emphasis: axes[index_i, index_j].plot(XT, TY, marker='o', linestyle=None, markersize=19, markeredgewidth=0.04, linewidth=2.1, color='g',zorder=10) else: axes[index_i, index_j].plot(XT[:], TY[:], marker='o', linestyle='-', markersize=12, markeredgewidth=0.01, linewidth=0.2, color=colors[int(epochsInds[index_in_range])]) utils.adjustAxes(axes[index_i, index_j], axis_font=axis_font, title_str=title_str, x_ticks=x_ticks, y_ticks=y_ticks, x_lim=[0, 25.1], y_lim=None, set_xlabel=index_i == axes.shape[0] - 1, set_ylabel=index_j == 0, x_label='$I(X;T)$', y_label='$I(T;Y)$', set_xlim=False, set_ylim=False, set_ticks=True, label_size=font_size) #Save the figure and add color bar if index_i ==axes.shape[0]-1 and index_j ==axes.shape[1]-1: utils.create_color_bar(f, cmap, colorbar_axis, bar_font, epochsInds, title='Epochs') f.savefig(save_name+'.jpg', dpi=500, format='jpg')
def __init__(self, gt, joints, dolegend=True, linewidth=1): """ Initialize class :type gt: groundtruth joints :type joints: calculated joints """ if not (isinstance(gt, numpy.ndarray) or isinstance(gt, list)) or not ( isinstance(joints, list) or isinstance(joints, numpy.ndarray)): raise ValueError("Params must be list or ndarray") if len(gt) != len(joints): print("Error: groundtruth has {} elements, eval data has {}".format(len(gt), len(joints))) raise ValueError("Params must be the same size") if len(gt) == len(joints) == 0: print("Error: groundtruth has {} elements, eval data has {}".format(len(gt), len(joints))) raise ValueError("Params must be of non-zero size") if gt[0].shape != joints[0].shape: print("Error: groundtruth has {} dims, eval data has {}".format(gt[0].shape, joints[0].shape)) raise ValueError("Params must be of same dimensionality") self.gt = numpy.asarray(gt) self.joints = numpy.asarray(joints) assert (self.gt.shape == self.joints.shape) self.colors = ['blue', 'green', 'red', 'cyan', 'magenta', 'black', 'brown', 'gray', 'indigo', 'pink', 'lightgreen', 'darkorange', 'peru', 'steelblue', 'turquoise'] self.linestyles = ['-'] # , '--', '-.', ':', '-', '--', '-.', ':'] self.linewidth = linewidth self.dolegend = dolegend self.subfolder = './eval/' self.visiblemask = numpy.ones((self.gt.shape[0], self.gt.shape[1], 3)) self.jointNames = None self.jointConnections = [] self.jointConnectionColors = [] self.plotMaxJointDist = 80 self.plotMeanJointDist = 80 self.plotMedianJointDist = 80 self.VTKviewport = [0, 0, 0, 0, 0]
def plotFramesWithinMax(self, basename, methodName='Our method', baseline=None): """ plot and save plot for fraction of frames within max distance :param basename: file basename :param methodName: our method name :param baseline: list of baselines as tuple (Name,evaluation object) :return: None """ if baseline is not None: for bs in baseline: if not (isinstance(bs[1], self.__class__)): raise TypeError('baseline must be of type {} but {} provided'.format(self.__class__.__name__, bs[1].__class__.__name__)) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot([self.getNumFramesWithinMaxDist(j) / float(self.joints.shape[0]) * 100. for j in range(0, self.plotMaxJointDist)], label=methodName, c=self.colors[0], linestyle=self.linestyles[0], linewidth=self.linewidth) bs_idx = 1 if baseline is not None: for bs in baseline: ax.plot([bs[1].getNumFramesWithinMaxDist(j) / float(self.joints.shape[0]) * 100. for j in range(0, self.plotMaxJointDist)], label=bs[0], c=self.colors[bs_idx % len(self.colors)], linestyle=self.linestyles[bs_idx % len(self.linestyles)], linewidth=self.linewidth) bs_idx += 1 plt.xlabel('Distance threshold / mm') plt.ylabel('Fraction of frames within distance / %') plt.ylim([0.0, 100.0]) ax.grid(True) if self.dolegend: # Put a legend below current axis handles, labels = ax.get_legend_handles_labels() # lgd = ax.legend(handles, labels, loc='lower right', ncol=1) #, bbox_to_anchor=(0.5,-0.1) lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=3) # ncol=2, prop={'size': 14}) bbea = (lgd,) else: bbea = None plt.show(block=False) fig.savefig('{}/{}_frameswithin.pdf'.format(self.subfolder, basename), bbox_extra_artists=bbea, bbox_inches='tight') plt.close(fig)