我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用matplotlib.cm.jet()。
def fast_run(args): model = Model(args) feed = {} #feed[model.train_batch]=False xx,ss,yy=model.inputs(args.input_path) sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) tf.train.start_queue_runners(sess=sess) xxx,sss,yyy=sess.run([xx,ss,yy]) #print(yyy) #print(yyy[1]) print('len:',xxx.shape) import matplotlib.cm as cm import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.figure(figsize=(16,4)) #plt.imshow() plt.imshow(np.asarray(xxx[0]).reshape((36,90))+0.5, interpolation='nearest', aspect='auto', cmap=cm.jet) plt.savefig("img.jpg") plt.clf() ; plt.cla()
def plot(self, n=200, rng=(-3.0,3.0, -4.0,8.0)): x = np.linspace(rng[0], rng[1], n) y = np.linspace(rng[2], rng[3], n) xx, yy = np.meshgrid(x, y) points = np.vstack((xx.ravel(), yy.ravel())).T values = self.eval(points) zz = values.reshape((xx.shape[0], yy.shape[1])) fig = plt.figure(figsize=(12,6)) axSurf = fig.add_subplot(1,2,1, projection='3d') surf = axSurf.plot_surface(xx, yy, zz, linewidth=1.0, cmap=pltcm.jet) surf.set_edgecolor('black') axCont = fig.add_subplot(1,2,2) axCont.contour(x, y, zz, 40, color='black') axCont.scatter(self.a, self.a**2, color='black', marker='o', s=400, linewidth=3) axCont.scatter(*self.solution, color='red', marker='x', s=400, linewidth=3) paramTrace = np.array(self.trainResult['pTrace']) axCont.plot(paramTrace[:,0], paramTrace[:,1], color='red', linewidth=2) fig.tight_layout()
def plot(self, n=500, rng=(-5.0,5.0, -5.0,5.0)): x = np.linspace(rng[0], rng[1], n) y = np.linspace(rng[2], rng[3], n) xx, yy = np.meshgrid(x, y) points = np.vstack((xx.ravel(), yy.ravel())).T values = self.eval(points) zz = values.reshape((xx.shape[0], yy.shape[1])) fig = plt.figure() axSurf = fig.add_subplot(1,2,1, projection='3d') surf = axSurf.plot_surface(xx, yy, zz, linewidth=1.0, cmap=pltcm.jet) surf.set_edgecolor('black') axCont = fig.add_subplot(1,2,2) axCont.contour(x, y, zz, 40, color='black') axCont.scatter(0.0, 0.0, color='black', marker='o', s=400, linewidth=3) axCont.scatter(*self.solution, color='red', marker='x', s=400, linewidth=3) paramTrace = np.array(self.trainResult['pTrace']) axCont.plot(paramTrace[:,0], paramTrace[:,1], color='red', linewidth=2)
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 plotValueFunction(self, valueFunction, prefix): '''3d plot of a value function.''' fig, ax = plt.subplots(subplot_kw = dict(projection = '3d')) X, Y = np.meshgrid(np.arange(self.numCols), np.arange(self.numRows)) Z = valueFunction.reshape(self.numRows, self.numCols) for i in xrange(len(X)): for j in xrange(len(X[i])/2): tmp = X[i][j] X[i][j] = X[i][len(X[i]) - j - 1] X[i][len(X[i]) - j - 1] = tmp my_col = cm.jet(np.random.rand(Z.shape[0],Z.shape[1])) ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = plt.get_cmap('jet')) plt.gca().view_init(elev=30, azim=30) plt.savefig(self.outputPath + prefix + 'value_function.png') plt.close()
def PrintDomain(Matrix, mesh, Elem = None): """ 3D plot of all elements given in the form of a list; Arguments: Elem(ndarray-int): list of elements to be plotted Matrix(ndarray-float): values to be plotted, should be equal in size to the first argument(Elem) mesh(CartesianMesh object): mesh object """ if Elem == None: Elem = np.arange(mesh.NumberOfElts) # if len(Matrix.shape)==1: # Matrix = np.reshape(Matrix, (mesh.ny, mesh.nx)) tmp = np.zeros((mesh.NumberOfElts,)) tmp[Elem] = Matrix fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_trisurf(mesh.CenterCoor[:, 0], mesh.CenterCoor[:, 1], tmp, cmap=cm.jet, linewidth=0.2) plt.show() plt.pause(0.01) # ----------------------------------------------------------------------------------------------------------------------
def test_kde_colors(self): tm._skip_if_no_scipy() _skip_if_no_scipy_gaussian_kde() from matplotlib import cm custom_colors = 'rgcby' df = DataFrame(rand(5, 5)) ax = df.plot.kde(color=custom_colors) self._check_colors(ax.get_lines(), linecolors=custom_colors) tm.close() ax = df.plot.kde(colormap='jet') rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df))) self._check_colors(ax.get_lines(), linecolors=rgba_colors) tm.close() ax = df.plot.kde(colormap=cm.jet) rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df))) self._check_colors(ax.get_lines(), linecolors=rgba_colors)
def plot4(): # Density 1 Z = gen_gaussian_plot_vals(x_hat, ?) cs1 = ax.contour(X, Y, Z, 6, colors="black") ax.clabel(cs1, inline=1, fontsize=10) # Density 2 M = ? * G.T * linalg.inv(G * ? * G.T + R) x_hat_F = x_hat + M * (y - G * x_hat) ?_F = ? - M * G * ? Z_F = gen_gaussian_plot_vals(x_hat_F, ?_F) cs2 = ax.contour(X, Y, Z_F, 6, colors="black") ax.clabel(cs2, inline=1, fontsize=10) # Density 3 new_x_hat = A * x_hat_F new_? = A * ?_F * A.T + Q new_Z = gen_gaussian_plot_vals(new_x_hat, new_?) cs3 = ax.contour(X, Y, new_Z, 6, colors="black") ax.clabel(cs3, inline=1, fontsize=10) ax.contourf(X, Y, new_Z, 6, alpha=0.6, cmap=cm.jet) ax.text(float(y[0]), float(y[1]), r"$y$", fontsize=20, color="black") # == Choose a plot to generate == #
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 = 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 xrange(N + 1)] return LinearSegmentedColormap(cmap.name + "_%d" % N, cdict, 1024)
def single_hgram(hgram, title=None, fname='sample.pdf', show=False, link=None): """ Show """ import matplotlib.cm as cm plt.figure(dpi=150, figsize=(6,2)) xs = list(range(len(hgram))) colors = [cm.jet(float(i)/max(hgram)) for i in hgram] for h in range(len(hgram)): b = plt.bar(xs[h], hgram[h], width=1., color=colors[h], edgecolor=colors[h]) #alpha=colors[h], # b.set_urls(['http://www.ytmnd.com']) # Aesthetics if title is not None: if link is not None: pass # Add a link here? else: plt.title(title) plt.xlabel('Base') plt.ylabel('Relative coverage') if fname is not None: plt.savefig(fname) if show: plt.show() return
def multi_hgram(hgrams, title=None, fname=None, show=False, link=None): """ """ import matplotlib.cm as cm plt.figure(dpi=150, figsize=(6,2)) xs = list(range(max([len(h) for h in hgrams]))) maxmax = max([max(hg) for hg in hgrams]) # Color each line thing for hgram in hgrams: colors = [cm.jet(float(i)/maxmax) for i in hgram] for h in range(len(hgram)): plt.scatter(xs[h], hgram[h], marker='o', color=colors[h], s=2) #edgecolor='none') #alpha=colors[h], plt.plot(xs[:len(hgram)], hgram, linewidth=1., color='k', alpha=0.4) if title is not None: plt.title(title) plt.xlabel('Base') plt.ylabel('Relative coverage') if fname is not None: plt.savefig(fname) if show: plt.show() return
def plot_stacked_power_generation(results, ax=None, kind='bar', legend=False): if ax is None: fig, axs = plt.subplots(1, 1, figsize=(16, 10)) ax = axs df = results.power_generated cols = (df - results.unit_commitment*results.maximum_power_output).std().sort_values().index df = df[[c for c in cols]] df.plot(kind=kind, stacked=True, ax=ax, colormap=cm.jet, alpha=0.5, legend=legend) df = results.unit_commitment * results.maximum_power_output df = df[[c for c in cols]] df.plot.area(stacked=True, ax=ax, alpha=0.125/2, colormap=cm.jet, legend=None) ax.set_ylabel('Dispatch and Committed Capacity (MW)') ax.set_xlabel('Time (h)') return ax
def run_sample(args): model = Model(args) y_, x, s, y = model.sample() print('correct text:',y) print('prediction :',y_) print('len:',s) print('batch shape:',x.shape) import matplotlib.cm as cm import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.figure(figsize=(16,4)) plt.imshow(np.asarray(x[0]).reshape((36,90))[:s[0]]+0.5, interpolation='nearest', aspect='auto', cmap=cm.jet) plt.savefig("img.jpg") plt.clf() ; plt.cla() print("image saved:img.jpg")
def demoPSO(): rosen = tests.Rosen(optimFunc=pso, nParticles=10, accuracy=0.01, maxIter=5000, verbose=True)#, initialSolution=(2.5, -2.5)) n = 200 rng=(-3.0,3.0, -4.0,8.0) x = np.linspace(rng[0], rng[1], n) y = np.linspace(rng[2], rng[3], n) xx, yy = np.meshgrid(x, y) points = np.vstack((xx.ravel(), yy.ravel())).T values = rosen.eval(points) zz = values.reshape((xx.shape[0], yy.shape[1])) fig = plt.figure(figsize=(12,6)) axSurf = fig.add_subplot(1,2,1, projection='3d') surf = axSurf.plot_surface(xx, yy, zz, linewidth=1.0, cmap=pltcm.jet) surf.set_edgecolor('black') axCont = fig.add_subplot(1,2,2) axCont.contour(x, y, zz, 40, color='black') axCont.scatter(rosen.a, rosen.a**2, color='black', marker='o', s=400, linewidth=3) axCont.scatter(*rosen.solution, color='red', marker='x', s=400, linewidth=3) paramTrace = np.array(rosen.trainResult['pTrace']) for i in xrange(paramTrace.shape[1]): axCont.plot(paramTrace[:,i:,0], paramTrace[:,i:,1], color=plt.cm.jet(i/float(paramTrace.shape[1])), linewidth=1) fig.tight_layout()
def plotTrajectory(data): # points = np.array([x, y]).T.reshape(-1, 1, 2) # segments = np.concatenate([points[:-1], points[1:]], axis=1) # # lc = LineCollection(segments, cmap=plt.get_cmap('Spectral')) # lc.set_array(z) # #lc.set_linewidth(2) # # plt.gca().add_collection(lc) import matplotlib.cm as cm cmap = cm.jet; c = np.linspace(0, 10, len(data[:,0])); plt.scatter(data[:,0], data[:,1], c = c, cmap = cmap, marker = '+');
def display(self, img, n_classes, labels=None, mask=None, interpolation='none', colorMap='jet', firstBlack=False, suffix=''): """ Display a classification map using matplotlib. Parameters: img: `numpy array` A classified map, (m x n x 1), the classes start at 0. n_classes: `int` The number of classes found in img. labels: `list of string [default None]` The legend labels. mask: `numpy array [default None]` A binary mask, when *True* the corresponding pixel is displayed. interpolation: `string [default none]` A matplotlib interpolation method. colorMap: `string [default 'Accent']` A color map element of ['Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3'], "Accent" is the default and it fall back on "Jet". firstBlack: `bool [default False]` Display the first legend element in black if *True*. If it is the case, the corresponding classification class value is zero and it can be use when the meaning is nothing to classify (example: a background). suffix: `string [default None]` Add a suffix to the file name. """ self.plot(img, n_classes, labels=labels, mask=mask, interpolation=interpolation, colorMap=colorMap, firstBlack=firstBlack, suffix=suffix)
def plot1(self, img, path=None, mask=None, interpolation='none', colorMap='jet', suffix=''): import matplotlib.pyplot as plt if path != None: plt.ioff() if isinstance(mask, np.ndarray): img = img[:,:] * mask plt.imshow(img, interpolation=interpolation) plt.set_cmap(colorMap) cbar = plt.colorbar() cbar.set_ticks([]) if path != None: if suffix == None: fout = osp.join(path, '{0}.png'.format(self.label)) else: fout = osp.join(path, '{0}_{1}.png'.format(self.label, suffix)) try: plt.savefig(fout) except IOError: raise IOError('in classifiers.output, no such file or directory: {0}'.format(path)) else: if suffix == None: plt.title('{0}'.format(self.label)) else: plt.title('{0} - {1}'.format(self.label, suffix)) plt.show() plt.close()
def plotBasisFunctions(self, eigenvalues, eigenvectors): '''3d plot of the basis function. Right now I am plotting eigenvectors, so each coordinate of the eigenvector correspond to the value to be plotted for the correspondent state.''' for i in xrange(len(eigenvalues)): fig, ax = plt.subplots(subplot_kw = dict(projection = '3d')) X, Y = np.meshgrid(np.arange(self.numRows), np.arange(self.numCols)) Z = eigenvectors[:,i].reshape(self.numCols, self.numRows) for ii in xrange(len(X)): for j in xrange(len(X[ii])/2): tmp = X[ii][j] X[ii][j] = X[ii][len(X[ii]) - j - 1] X[ii][len(X[ii]) - j - 1] = tmp my_col = cm.jet(np.random.rand(Z.shape[0],Z.shape[1])) ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = plt.get_cmap('jet')) plt.gca().view_init(elev=30, azim=30) plt.savefig(self.outputPath + str(i) + '_eig' + '.png') plt.close() plt.plot(eigenvalues, 'o') plt.savefig(self.outputPath + 'eigenvalues.png')
def test_radviz(self): from pandas.tools.plotting import radviz from matplotlib import cm df = self.iris _check_plot_works(radviz, frame=df, class_column='Name') rgba = ('#556270', '#4ECDC4', '#C7F464') ax = _check_plot_works( radviz, frame=df, class_column='Name', color=rgba) # skip Circle drawn as ticks patches = [p for p in ax.patches[:20] if p.get_label() != ''] self._check_colors( patches[:10], facecolors=rgba, mapping=df['Name'][:10]) cnames = ['dodgerblue', 'aquamarine', 'seagreen'] _check_plot_works(radviz, frame=df, class_column='Name', color=cnames) patches = [p for p in ax.patches[:20] if p.get_label() != ''] self._check_colors(patches, facecolors=cnames, mapping=df['Name'][:10]) _check_plot_works(radviz, frame=df, class_column='Name', colormap=cm.jet) cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique())) patches = [p for p in ax.patches[:20] if p.get_label() != ''] self._check_colors(patches, facecolors=cmaps, mapping=df['Name'][:10]) colors = [[0., 0., 1., 1.], [0., 0.5, 1., 1.], [1., 0., 0., 1.]] df = DataFrame({"A": [1, 2, 3], "B": [2, 1, 3], "C": [3, 2, 1], "Name": ['b', 'g', 'r']}) ax = radviz(df, 'Name', color=colors) handles, labels = ax.get_legend_handles_labels() self._check_colors(handles, facecolors=colors)
def test_bar_colors(self): import matplotlib.pyplot as plt default_colors = self._maybe_unpack_cycler(plt.rcParams) df = DataFrame(randn(5, 5)) ax = df.plot.bar() self._check_colors(ax.patches[::5], facecolors=default_colors[:5]) tm.close() custom_colors = 'rgcby' ax = df.plot.bar(color=custom_colors) self._check_colors(ax.patches[::5], facecolors=custom_colors) tm.close() from matplotlib import cm # Test str -> colormap functionality ax = df.plot.bar(colormap='jet') rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() # Test colormap functionality ax = df.plot.bar(colormap=cm.jet) rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() ax = df.ix[:, [0]].plot.bar(color='DodgerBlue') self._check_colors([ax.patches[0]], facecolors=['DodgerBlue']) tm.close() ax = df.plot(kind='bar', color='green') self._check_colors(ax.patches[::5], facecolors=['green'] * 5) tm.close()
def draw_mandelbrot(cx, cy, d): """ ???(cx, cy)????d????Mandelbrot """ x0, x1, y0, y1 = cx-d, cx+d, cy-d, cy+d y, x = np.ogrid[y0:y1:200j, x0:x1:200j] c = x + y*1j start = time.clock() mandelbrot = np.frompyfunc(iter_point,1,1)(c).astype(np.float) print("time=",time.clock() - start) pl.imshow(mandelbrot, cmap=cm.jet, extent=[x0,x1,y0,y1]) #pl.gca().set_axis_off()
def plot1(): Z = gen_gaussian_plot_vals(x_hat, ?) ax.contourf(X, Y, Z, 6, alpha=0.6, cmap=cm.jet) cs = ax.contour(X, Y, Z, 6, colors="black") ax.clabel(cs, inline=1, fontsize=10)
def plot2(): Z = gen_gaussian_plot_vals(x_hat, ?) ax.contourf(X, Y, Z, 6, alpha=0.6, cmap=cm.jet) cs = ax.contour(X, Y, Z, 6, colors="black") ax.clabel(cs, inline=1, fontsize=10) ax.text(float(y[0]), float(y[1]), r"$y$", fontsize=20, color="black")
def plot3(): Z = gen_gaussian_plot_vals(x_hat, ?) cs1 = ax.contour(X, Y, Z, 6, colors="black") ax.clabel(cs1, inline=1, fontsize=10) M = ? * G.T * linalg.inv(G * ? * G.T + R) x_hat_F = x_hat + M * (y - G * x_hat) ?_F = ? - M * G * ? new_Z = gen_gaussian_plot_vals(x_hat_F, ?_F) cs2 = ax.contour(X, Y, new_Z, 6, colors="black") ax.clabel(cs2, inline=1, fontsize=10) ax.contourf(X, Y, new_Z, 6, alpha=0.6, cmap=cm.jet) ax.text(float(y[0]), float(y[1]), r"$y$", fontsize=20, color="black")
def plot_segmentation(I,GT,Seg, fig=None): I = np.squeeze(I) GT = np.squeeze(GT) Seg = np.squeeze(Seg) GTC = np.logical_and(GT, np.logical_not(ndimage.binary_erosion(GT))) SegC = np.logical_and(Seg, np.logical_not(ndimage.binary_erosion(Seg))) plt.figure(fig) maskedGT = np.ma.masked_where(GTC == 0, GTC) maskedSeg = np.ma.masked_where(SegC == 0, SegC) plt.imshow(I, cmap=cm.gray) plt.imshow(maskedGT, cmap=cm.jet, interpolation='none') plt.imshow(maskedSeg*100, cmap=cm.hsv, interpolation='none')
def plot_decision_boundary_non_block(weight, input, z, layer_num, neuron_num, activ_type): x = np.ravel(input[:,0]) y = np.ravel(input[:,1]) fig1 = plt.figure(1) # plt.hold(True) # weight = np.column_stack((np.column_stack((weight[0:3],weight[3:6])),weight[6:9])) x_s=np.arange(np.amin(x), np.amax(x), 0.1) # generate a mesh y_s=np.arange(np.amin(y), np.amax(y), 0.1) x_surf, y_surf = np.meshgrid(x_s, y_s) xy=np.vstack((x_surf.flatten(),y_surf.flatten())).T # xy = np.column_stack((np.ones(np.shape(xy)[0]), xy)) logit = test_neural(weight, xy, layer_num, neuron_num, activ_type) #xy.dot(weight) # N x K boundary = np.zeros(xy.shape[0]) # N for i in range(xy.shape[0]): boundary[i] = np.argmax(logit[i]) z_surf = np.zeros(np.shape(xy)[0]) z_surf[np.where(boundary==0)] = 1 z_surf[np.where(boundary==1)] = 2 z_surf[np.where(boundary==2)] = 3 z_surf = z_surf.reshape(x_surf.shape) plt.contourf(x_surf,y_surf,z_surf, 8, alpha=.75, cmap='jet') plt.scatter(x, y, s=20,c=z, marker = 'o', cmap = cm.jet ); # plot a 3d scatter plot plt.draw() plt.pause(0.001) return boundary
def plot_decision_boundary(weight, input, z, layer_num, neuron_num, activ_type): x = np.ravel(input[:,0]) y = np.ravel(input[:,1]) fig1 = plt.figure(1) plt.hold(True) x_s=np.arange(np.amin(x), np.amax(x), 0.01) # generate a mesh y_s=np.arange(np.amin(y), np.amax(y), 0.01) x_surf, y_surf = np.meshgrid(x_s, y_s) xy=np.vstack((x_surf.flatten(),y_surf.flatten())).T logit = test_neural(weight, xy, layer_num, neuron_num, activ_type) #xy.dot(weight) # N x K boundary = np.zeros(xy.shape[0]) # N for i in range(xy.shape[0]): boundary[i] = np.argmax(logit[i]) z_surf = np.zeros(np.shape(xy)[0]) z_surf[np.where(boundary==0)] = 1 z_surf[np.where(boundary==1)] = 2 z_surf[np.where(boundary==2)] = 3 z_surf = z_surf.reshape(x_surf.shape) plt.contourf(x_surf,y_surf,z_surf, 8, alpha=.75, cmap='jet') plt.scatter(x, y, s=20,c=z, marker = 'o', cmap = cm.jet ); # plot a 3d scatter plot plt.show() return boundary
def plot_silhouettes(X, y): cluster_labels = np.unique(y) n_clusters = cluster_labels.shape[0] silhouette_vals = silhouette_samples(X, y, metric='euclidean') y_ax_lower = 0 y_ax_upper = 0 yticks = [] for i, c in enumerate(cluster_labels): c_silhouette_vals = silhouette_vals[y == c] c_silhouette_vals.sort() y_ax_upper += len(c_silhouette_vals) color = cm.jet(i / n_clusters) plt.barh( range(y_ax_lower, y_ax_upper), c_silhouette_vals, height=1.0, edgecolor='none', color=color, ) yticks.append((y_ax_lower + y_ax_upper) / 2) y_ax_lower += len(c_silhouette_vals) silhouette_avg = np.mean(silhouette_vals) plt.axvline(silhouette_avg, color='red', linestyle='--') plt.yticks(yticks, cluster_labels + 1) plt.ylabel('Cluster') plt.xlabel('Silhouette coefficient') plt.show()
def __init__(self, max_x, max_y, data_source=None): Duration.__init__(self, max_x, max_y, data_source) self.cmap = cm.jet # pylint: disable=no-member self.label_fmt = '{}' # until voluptuous bug fix is released self.val_fmt = '{:> .1f}'
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None): """Wrapper around pl.imshow""" if cmap is None: cmap = cm.jet if vmin is None: vmin = data.min() if vmax is None: vmax = data.max() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap) pl.colorbar(im, cax=cax)
def set_image_options(self, args=None, figsize="6x6", dpi=300, format="pdf", font="Helvetica", palette="deep", style="darkgrid", cmap="jet"): """ Add image format options for given command line programs. """ allowed_format = ("emf", "eps", "pdf", "png", "ps", \ "raw", "rgba", "svg", "svgz") allowed_fonts = ("Helvetica", "Palatino", "Schoolbook", "Arial") allowed_styles = ("darkgrid", "whitegrid", "dark", "white", "ticks") allowed_diverge = ("BrBG", "PiYG", "PRGn", "PuOr", "RdBu", \ "RdGy", "RdYlBu", "RdYlGn", "Spectral") group = OptionGroup(self, "Image options") self.add_option_group(group) group.add_option("--figsize", default=figsize, help="Figure size `width`x`height` in inches [default: %default]") group.add_option("--dpi", default=dpi, type="int", help="Physical dot density (dots per inch) [default: %default]") group.add_option("--format", default=format, choices=allowed_format, help="Generate image of format [default: %default]") group.add_option("--font", default=font, choices=allowed_fonts, help="Font name") group.add_option("--style", default=style, choices=allowed_styles, help="Axes background") group.add_option("--diverge", default="PiYG", choices=allowed_diverge, help="Contrasting color scheme") group.add_option("--cmap", default=cmap, help="Use this color map") if args is None: args = sys.argv[1:] opts, args = self.parse_args(args) assert opts.dpi > 0 assert "x" in opts.figsize setup_theme(style=opts.style, font=opts.font) return opts, args, ImageOptions(opts)
def test_ElasticNet_alpha_rho(*data): ''' test score with different alpha and l1_ratio :param data: train_data, test_data, train_value, test_value :return: None ''' X_train,X_test,y_train,y_test=data alphas=np.logspace(-2,2) rhos=np.linspace(0.01,1) scores=[] for alpha in alphas: for rho in rhos: regr = linear_model.ElasticNet(alpha=alpha,l1_ratio=rho) regr.fit(X_train, y_train) scores.append(regr.score(X_test, y_test)) ## graph alphas, rhos = np.meshgrid(alphas, rhos) scores=np.array(scores).reshape(alphas.shape) from mpl_toolkits.mplot3d import Axes3D # this part works well in py3 from matplotlib import cm fig=plt.figure() ax=Axes3D(fig) surf = ax.plot_surface(alphas, rhos, scores, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False) fig.colorbar(surf, shrink=0.5, aspect=5) ax.set_xlabel(r"$\alpha$") ax.set_ylabel(r"$\rho$") ax.set_zlabel("score") ax.set_title("ElasticNet") plt.show()
def vis_value_map(pred, targ, save_path, title='prediction', share=True): # print 'in vis: ', pred.shape, targ.shape dim = int(math.sqrt(pred.size)) if share: vmin = min(pred.min(), targ.min()) vmax = max(pred.max(), targ.max()) else: vmin = None vmax = None plt.clf() fig, (ax0,ax1) = plt.subplots(1,2,sharey=True) heat0 = ax0.pcolor(pred.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cm.jet) ax0.set_title(title, fontsize=5) if not share: fig.colorbar(heat0) heat1 = ax1.pcolor(targ.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cm.jet) ax1.invert_yaxis() ax1.set_title('target') fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(heat1, cax=cbar_ax) # print 'saving to: ', fullpath plt.savefig(save_path, bbox_inches='tight') plt.close(fig) # print pred.shape, targ.shape
def vis_fig(data, save_path, title=None, vmax=None, vmin=None, cmap=cm.jet): # print 'in vis: ', pred.shape, targ.shape dim = int(math.sqrt(data.size)) # if share: # vmin = min(pred.min(), targ.min()) # vmax = max(pred.max(), targ.max()) # else: # vmin = None # vmax = None plt.clf() # fig, (ax0,ax1) = plt.subplots(1,2,sharey=True) plt.pcolor(data.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cmap) plt.xticks([]) plt.yticks([]) # ax0.set_title(title, fontsize=5) # if not share: # fig.colorbar(heat0) # heat1 = ax1.pcolor(targ.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cm.jet) fig = plt.gcf() ax = plt.gca() if title: ax.set_title(title) ax.invert_yaxis() fig.set_size_inches(4,4) # ax1.invert_yaxis() # ax1.set_title('target') # fig.subplots_adjust(right=0.8) # cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) # fig.colorbar(heat1, cax=cbar_ax) # print 'saving to: ', fullpath plt.savefig(save_path, bbox_inches='tight', pad_inches=0.0) plt.close(fig) # print pred.shape, targ.shape
def plot_perturbation(model, model1, colorbar=True): """ Plot a two-dimensional velocity difference from two seismic :class:`Model` objects. :param model: :class:`Model` object of first velocity model. :param model1: :class:`Model` object of the second velocity model. :param source: Coordinates of the source point. :param receiver: Coordinates of the receiver points. """ domain_size = 1.e-3 * np.array(model.domain_size) extent = [model.origin[0], model.origin[0] + domain_size[0], model.origin[1] + domain_size[1], model.origin[1]] dv = np.transpose(model.vp) - np.transpose(model1.vp) plot = plt.imshow(dv, animated=True, cmap=cm.jet, vmin=min(dv.reshape(-1)), vmax=max(dv.reshape(-1)), extent=extent) plt.xlabel('X position (km)') plt.ylabel('Depth (km)') # Create aligned colorbar on the right if colorbar: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(plot, cax=cax) cbar.set_label('Velocity perturbation (km/s)') plt.show()
def plot_velocity(model, source=None, receiver=None, colorbar=True): """ Plot a two-dimensional velocity field from a seismic :class:`Model` object. Optionally also includes point markers for sources and receivers. :param model: :class:`Model` object that holds the velocity model. :param source: Coordinates of the source point. :param receiver: Coordinates of the receiver points. """ domain_size = 1.e-3 * np.array(model.domain_size) extent = [model.origin[0], model.origin[0] + domain_size[0], model.origin[1] + domain_size[1], model.origin[1]] plot = plt.imshow(np.transpose(model.vp), animated=True, cmap=cm.jet, vmin=np.min(model.vp), vmax=np.max(model.vp), extent=extent) plt.xlabel('X position (km)') plt.ylabel('Depth (km)') # Plot source points, if provided if receiver is not None: plt.scatter(1e-3*receiver[:, 0], 1e-3*receiver[:, 1], s=25, c='green', marker='D') # Plot receiver points, if provided if source is not None: plt.scatter(1e-3*source[:, 0], 1e-3*source[:, 1], s=25, c='red', marker='o') # Ensure axis limits plt.xlim(model.origin[0], model.origin[0] + domain_size[0]) plt.ylim(model.origin[1] + domain_size[1], model.origin[1]) # Create aligned colorbar on the right if colorbar: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(plot, cax=cax) cbar.set_label('Velocity (km/s)') plt.show()
def plot_costs(case, number_of_segments=1, ax=None, legend=True): if ax is None: fig, axs = plt.subplots(1, 1, figsize=(16, 10)) ax = axs color_scale = make_interpolater(0, len(case.gen_name), 0, 1) color = {g: plt.cm.jet(color_scale(i)) for i, g in enumerate(case.gen_name)} for s in calculate_segments(case, number_of_segments=number_of_segments): pmin, pmax = s['segment'] x = np.linspace(pmin, pmax) y = x * s['slope'] ax.plot(x, y, color=color[s['name']]) ax = ax.twinx() for s in calculate_segments(case, number_of_segments=number_of_segments): pmin, pmax = s['segment'] x = np.linspace(pmin, pmax) y = [s['slope'] for _ in x] ax.plot(x, y, color=color[s['name']]) ax.set_ylim(0, 1.2*y[-1]) if legend: lines = list() for g in case.gen_name: lines.append(mlines.Line2D([], [], color=color[g], label=g)) ax.legend(handles=lines, loc='upper left') return ax
def visualize_saliency(model, layer_idx, filter_indices, seed_img, alpha=0.5): """Generates an attention heatmap over the `seed_img` for maximizing `filter_indices` output in the given `layer`. For a full description of saliency, see the paper: [Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps](https://arxiv.org/pdf/1312.6034v2.pdf) Args: model: The `keras.models.Model` instance. Model input is expected to be a 4D image input of shape: `(samples, channels, rows, cols)` if data_format='channels_first' or `(samples, rows, cols, channels)` if data_format='channels_last'. layer_idx: The layer index within `model.layers` whose filters needs to be visualized. filter_indices: filter indices within the layer to be maximized. For `keras.layers.Dense` layer, `filter_idx` is interpreted as the output index. If you are visualizing final `keras.layers.Dense` layer, you tend to get better results with 'linear' activation as opposed to 'softmax'. This is because 'softmax' output can be maximized by minimizing scores for other classes. seed_img: The input image for which activation map needs to be visualized. alpha: The alpha value of image as overlayed onto the heatmap. This value needs to be between [0, 1], with 0 being heatmap only to 1 being image only (Default value = 0.5) Example: If you wanted to visualize attention over 'bird' category, say output index 22 on the final `keras.layers.Dense` layer, then, `filter_indices = [22]`, `layer = dense_layer`. One could also set filter indices to more than one value. For example, `filter_indices = [22, 23]` should (hopefully) show attention map that corresponds to both 22, 23 output categories. Returns: The heatmap image, overlayed with `seed_img` using `alpha`, indicating image regions that, when changed, would contribute the most towards maximizing the output of `filter_indices`. """ if alpha < 0. or alpha > 1.: raise ValueError("`alpha` needs to be between [0, 1]") filter_indices = utils.listify(filter_indices) print("Working on filters: {}".format(pprint.pformat(filter_indices))) losses = [ (ActivationMaximization(model.layers[layer_idx], filter_indices), 1) ] opt = Optimizer(model.input, losses) grads = opt.minimize(max_iter=1, verbose=False, seed_img=seed_img)[1] # We are minimizing loss as opposed to maximizing output as with the paper. # So, negative gradients here mean that they reduce loss, maximizing class probability. grads *= -1 s, c, row, col = utils.get_img_indices() grads = np.max(np.abs(grads), axis=c) # Normalize and zero out low probabilities for a cleaner output. grads /= np.max(grads) heatmap = np.uint8(cm.jet(grads)[..., :3] * 255) heatmap[np.where(grads < 0.2)] = 0 heatmap = np.uint8(seed_img * alpha + heatmap * (1. - alpha)) return grads
def _init_plot(self, dir, var, **kwargs): """ Internal method used by all plotting commands """ #self.cla() null = kwargs.pop('zorder', None) #Init of the bins array if not set bins = kwargs.pop('bins', None) if bins is None: bins = np.linspace(np.min(var), np.max(var), 6) if isinstance(bins, int): bins = np.linspace(np.min(var), np.max(var), bins) bins = np.asarray(bins) nbins = len(bins) #Number of sectors nsector = kwargs.pop('nsector', None) if nsector is None: nsector = 16 #Sets the colors table based on the colormap or the "colors" argument colors = kwargs.pop('colors', None) cmap = kwargs.pop('cmap', None) if colors is not None: if isinstance(colors, str): colors = [colors]*nbins if isinstance(colors, (tuple, list)): if len(colors) != nbins: raise ValueError("colors and bins must have same length") else: if cmap is None: cmap = cm.jet colors = self._colors(cmap, nbins) #Building the angles list angles = np.arange(0, -2*np.pi, -2*np.pi/nsector) + np.pi/2 normed = kwargs.pop('normed', False) blowto = kwargs.pop('blowto', False) #Set the global information dictionnary self._info['dir'], self._info['bins'], self._info['table'] = histogram(dir, var, bins, nsector, normed, blowto) return bins, nbins, nsector, colors, angles, kwargs
def kcv_errors(errors, range_x, range_y, label_x, label_y): r"""Plot a 3D error surface. Parameters ---------- errors : (N, D) ndarray Error matrix. range_x : array_like of N values First axis values. range_y : array_like of D values Second axis values. label_x : str First axis label. label_y : str Second axis label. Examples -------- >>> errors = numpy.empty((20, 10)) >>> x = numpy.arange(20) >>> y = numpy.arange(10) >>> for i in range(20): ... for j in range(10): ... errors[i, j] = (x[i] * y[j]) ... >>> kcv_errors(errors, x, y, 'x', 'y') >>> plt.show() """ fig = plt.figure() ax = Axes3D(fig) x_vals, y_vals = np.meshgrid(range_x, range_y) x_idxs, y_idxs = np.meshgrid(np.arange(len(range_x)), np.arange(len(range_y))) ax.set_xlabel(label_x) ax.set_ylabel(label_y) ax.set_zlabel('$error$') ax.plot_surface(x_vals, y_vals, errors[x_idxs, y_idxs], rstride=1, cstride=1, cmap=cm.jet)
def updateView(self, force=False, xRange=None): if self.changed: s = self.surface s.clear() for d in self.data: n = d.shape[0] // 50 # plot max 50x50 planes if n < 1: n = 1 data = d.transpose(2, 0, 1) s.plot_surface( data[ 0, ::n, ::n], data[ 1, ::n, ::n], data[ 2, ::n, ::n], cmap=cm.jet) # s._changed = False # s.pbaspect = [1.0, 1.0, 1.0] if xRange is not None: s.set_xlim(xRange) # if yRange != None: # s.set_ylim(yRange) # if zRange != None: # if xRange: # s.get_zlim() # s.set_zlim(zRange) s.pbaspect = [1, 1, 1] # else: # s.set_zlim(s.get_zlim()) # s.axis('equal') # s.invert_zaxis() self.fig.tight_layout() self.draw() self.changed = False # if d.changed: # self.curves[n].updateItems() # d.changed = False # class _PlotData(list): # def __init__(self, l): # list.__init__(self, l) # self.changed = True
def plot_fracture(self, Elem_Identifier, Parameter_Identifier, analytical=0, identify=[], mat_Properties=None): """ Plots the given parameter of the specified cells; Arguments: Elem_Identifier(string): elements to be printed; possible options: complete channel crack ribbon Parameter_Identifier(string): parameter to be ploted; possible options: width pressure viscosity footPrint analytical (float): radius of fracture footprint calculated analytically. not plotted if not given. (or Zero ?) evol (boolean): fracture evolution plot flag. Set to true will print fracture evolution with time. identify (ndarray): plot the cells in the provided list with cell number and different color to identify. This option can be used in debugging. perpendicular (bool): if true, perpendicular from the zero vertex on the fracture fron will be drawn. This can be used for debugging. """ if Elem_Identifier == 'complete': Elts = np.arange(self.mesh.NumberOfElts) elif Elem_Identifier == 'channel': Elts = self.EltChannel elif Elem_Identifier == 'crack': Elts = self.EltCrack elif Elem_Identifier == 'ribbon': Elts = self.EltRibbon elif Elem_Identifier == 'tip': Elts = self.EltTip else: print('invalid element identifier') return values = np.zeros((self.mesh.NumberOfElts), float) if Parameter_Identifier == 'width': values[Elts] = self.w[Elts] elif Parameter_Identifier == 'pressure': values[Elts] = self.p[Elts] elif Parameter_Identifier == 'muPrime': values[Elts] = self.muPrime[Elts] elif Parameter_Identifier == 'footPrint': fig = self.print_fracture_trace(analytical, identify, mat_Properties) return fig else: print('invalid parameter identifier') return None fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_trisurf(self.mesh.CenterCoor[:, 0], self.mesh.CenterCoor[:, 1], values, cmap=cm.jet, linewidth=0.2) return fig ######################################
def product_raw_stats(): df = pd.read_csv('/Users/srinath/playground/data-science/BimboInventoryDemand/train.csv') #df = pd.read_csv('/Users/srinath/playground/data-science/BimboInventoryDemand/trainitems300.csv') grouped = df.groupby(['Semana'])['Demanda_uni_equil'].mean() plt.figure(1, figsize=(20,10)) plt.subplot(321) plt.xlabel('Semana', fontsize=18) plt.ylabel('Mean', fontsize=18) #plt.yscale('log') #plt.xscale('log') plt.scatter(df['Semana'].values, df['Demanda_uni_equil'].values, alpha=0.5) grouped = df.groupby(['Semana'])['Demanda_uni_equil'].mean() plt.subplot(322) plt.xlabel('Slope', fontsize=18) plt.ylabel('Mean Error', fontsize=18) plt.scatter(grouped.index.values, grouped.values, alpha=0.5) grouped = df.groupby(['Semana', 'Producto_ID'])['Demanda_uni_equil'].mean() valuesDf = grouped.to_frame("Mean") valuesDf.reset_index(inplace=True) plt.subplot(323) plt.xlabel('Semana', fontsize=18) plt.ylabel('Mean Error', fontsize=18) plt.scatter(valuesDf['Semana'], valuesDf["Mean"], alpha=0.5) grouped = df.groupby(['Semana', 'Producto_ID'])['Demanda_uni_equil'].count() valuesDf = grouped.to_frame("count") valuesDf.reset_index(inplace=True) plt.subplot(324) X = valuesDf['Semana'] Y = valuesDf['Producto_ID'] plt.hexbin(valuesDf['Semana'], valuesDf['Producto_ID'], C=valuesDf['count'], cmap=CM.jet, gridsize=30, bins=50) plt.axis([X.min(), X.max(), Y.min(), Y.max()]) cb = plt.colorbar() cb.set_label('mean value') plt.tight_layout() plt.show()
def test_parallel_coordinates(self): from pandas.tools.plotting import parallel_coordinates from matplotlib import cm df = self.iris ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name') nlines = len(ax.get_lines()) nxticks = len(ax.xaxis.get_ticklabels()) rgba = ('#556270', '#4ECDC4', '#C7F464') ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', color=rgba) self._check_colors( ax.get_lines()[:10], linecolors=rgba, mapping=df['Name'][:10]) cnames = ['dodgerblue', 'aquamarine', 'seagreen'] ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', color=cnames) self._check_colors( ax.get_lines()[:10], linecolors=cnames, mapping=df['Name'][:10]) ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', colormap=cm.jet) cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique())) self._check_colors( ax.get_lines()[:10], linecolors=cmaps, mapping=df['Name'][:10]) ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', axvlines=False) assert len(ax.get_lines()) == (nlines - nxticks) colors = ['b', 'g', 'r'] df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3], "Name": colors}) ax = parallel_coordinates(df, 'Name', color=colors) handles, labels = ax.get_legend_handles_labels() self._check_colors(handles, linecolors=colors) with tm.assert_produces_warning(FutureWarning): parallel_coordinates(data=df, class_column='Name') with tm.assert_produces_warning(FutureWarning): parallel_coordinates(df, 'Name', colors=colors)
def test_line_colors(self): import sys from matplotlib import cm custom_colors = 'rgcby' df = DataFrame(randn(5, 5)) ax = df.plot(color=custom_colors) self._check_colors(ax.get_lines(), linecolors=custom_colors) tmp = sys.stderr sys.stderr = StringIO() try: tm.close() ax2 = df.plot(colors=custom_colors) lines2 = ax2.get_lines() for l1, l2 in zip(ax.get_lines(), lines2): self.assertEqual(l1.get_color(), l2.get_color()) finally: sys.stderr = tmp tm.close() ax = df.plot(colormap='jet') rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df))) self._check_colors(ax.get_lines(), linecolors=rgba_colors) tm.close() ax = df.plot(colormap=cm.jet) rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df))) self._check_colors(ax.get_lines(), linecolors=rgba_colors) tm.close() # make color a list if plotting one column frame # handles cases like df.plot(color='DodgerBlue') ax = df.ix[:, [0]].plot(color='DodgerBlue') self._check_colors(ax.lines, linecolors=['DodgerBlue']) ax = df.plot(color='red') self._check_colors(ax.get_lines(), linecolors=['red'] * 5) tm.close() # GH 10299 custom_colors = ['#FF0000', '#0000FF', '#FFFF00', '#000000', '#FFFFFF'] ax = df.plot(color=custom_colors) self._check_colors(ax.get_lines(), linecolors=custom_colors) tm.close() with tm.assertRaises(ValueError): # Color contains shorthand hex value results in ValueError custom_colors = ['#F00', '#00F', '#FF0', '#000', '#FFF'] # Forced show plot _check_plot_works(df.plot, color=custom_colors)
def test_area_colors(self): from matplotlib import cm from matplotlib.collections import PolyCollection custom_colors = 'rgcby' df = DataFrame(rand(5, 5)) ax = df.plot.area(color=custom_colors) self._check_colors(ax.get_lines(), linecolors=custom_colors) poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)] self._check_colors(poly, facecolors=custom_colors) handles, labels = ax.get_legend_handles_labels() # legend is stored as Line2D, thus check linecolors linehandles = [x for x in handles if not isinstance(x, PolyCollection)] self._check_colors(linehandles, linecolors=custom_colors) for h in handles: self.assertTrue(h.get_alpha() is None) tm.close() ax = df.plot.area(colormap='jet') jet_colors = lmap(cm.jet, np.linspace(0, 1, len(df))) self._check_colors(ax.get_lines(), linecolors=jet_colors) poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)] self._check_colors(poly, facecolors=jet_colors) handles, labels = ax.get_legend_handles_labels() linehandles = [x for x in handles if not isinstance(x, PolyCollection)] self._check_colors(linehandles, linecolors=jet_colors) for h in handles: self.assertTrue(h.get_alpha() is None) tm.close() # When stacked=False, alpha is set to 0.5 ax = df.plot.area(colormap=cm.jet, stacked=False) self._check_colors(ax.get_lines(), linecolors=jet_colors) poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)] jet_with_alpha = [(c[0], c[1], c[2], 0.5) for c in jet_colors] self._check_colors(poly, facecolors=jet_with_alpha) handles, labels = ax.get_legend_handles_labels() # Line2D can't have alpha in its linecolor self._check_colors(handles[:len(jet_colors)], linecolors=jet_colors) for h in handles: self.assertEqual(h.get_alpha(), 0.5)
def test_kde_colors_and_styles_subplots(self): tm._skip_if_no_scipy() _skip_if_no_scipy_gaussian_kde() from matplotlib import cm default_colors = self._maybe_unpack_cycler(self.plt.rcParams) df = DataFrame(randn(5, 5)) axes = df.plot(kind='kde', subplots=True) for ax, c in zip(axes, list(default_colors)): self._check_colors(ax.get_lines(), linecolors=[c]) tm.close() # single color char axes = df.plot(kind='kde', color='k', subplots=True) for ax in axes: self._check_colors(ax.get_lines(), linecolors=['k']) tm.close() # single color str axes = df.plot(kind='kde', color='red', subplots=True) for ax in axes: self._check_colors(ax.get_lines(), linecolors=['red']) tm.close() custom_colors = 'rgcby' axes = df.plot(kind='kde', color=custom_colors, subplots=True) for ax, c in zip(axes, list(custom_colors)): self._check_colors(ax.get_lines(), linecolors=[c]) tm.close() rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df))) for cmap in ['jet', cm.jet]: axes = df.plot(kind='kde', colormap=cmap, subplots=True) for ax, c in zip(axes, rgba_colors): self._check_colors(ax.get_lines(), linecolors=[c]) tm.close() # make color a list if plotting one column frame # handles cases like df.plot(color='DodgerBlue') axes = df.ix[:, [0]].plot(kind='kde', color='DodgerBlue', subplots=True) self._check_colors(axes[0].lines, linecolors=['DodgerBlue']) # single character style axes = df.plot(kind='kde', style='r', subplots=True) for ax in axes: self._check_colors(ax.get_lines(), linecolors=['r']) tm.close() # list of styles styles = list('rgcby') axes = df.plot(kind='kde', style=styles, subplots=True) for ax, c in zip(axes, styles): self._check_colors(ax.get_lines(), linecolors=[c]) tm.close()
def test_boxplot_colors(self): def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c='k', fliers_c='b'): self._check_colors(bp['boxes'], linecolors=[box_c] * len(bp['boxes'])) self._check_colors(bp['whiskers'], linecolors=[whiskers_c] * len(bp['whiskers'])) self._check_colors(bp['medians'], linecolors=[medians_c] * len(bp['medians'])) self._check_colors(bp['fliers'], linecolors=[fliers_c] * len(bp['fliers'])) self._check_colors(bp['caps'], linecolors=[caps_c] * len(bp['caps'])) default_colors = self._maybe_unpack_cycler(self.plt.rcParams) df = DataFrame(randn(5, 5)) bp = df.plot.box(return_type='dict') _check_colors(bp, default_colors[0], default_colors[0], default_colors[2]) tm.close() dict_colors = dict(boxes='#572923', whiskers='#982042', medians='#804823', caps='#123456') bp = df.plot.box(color=dict_colors, sym='r+', return_type='dict') _check_colors(bp, dict_colors['boxes'], dict_colors['whiskers'], dict_colors['medians'], dict_colors['caps'], 'r') tm.close() # partial colors dict_colors = dict(whiskers='c', medians='m') bp = df.plot.box(color=dict_colors, return_type='dict') _check_colors(bp, default_colors[0], 'c', 'm') tm.close() from matplotlib import cm # Test str -> colormap functionality bp = df.plot.box(colormap='jet', return_type='dict') jet_colors = lmap(cm.jet, np.linspace(0, 1, 3)) _check_colors(bp, jet_colors[0], jet_colors[0], jet_colors[2]) tm.close() # Test colormap functionality bp = df.plot.box(colormap=cm.jet, return_type='dict') _check_colors(bp, jet_colors[0], jet_colors[0], jet_colors[2]) tm.close() # string color is applied to all artists except fliers bp = df.plot.box(color='DodgerBlue', return_type='dict') _check_colors(bp, 'DodgerBlue', 'DodgerBlue', 'DodgerBlue', 'DodgerBlue') # tuple is also applied to all artists except fliers bp = df.plot.box(color=(0, 1, 0), sym='#123456', return_type='dict') _check_colors(bp, (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), '#123456') with tm.assertRaises(ValueError): # Color contains invalid key results in ValueError df.plot.box(color=dict(boxes='red', xxxx='blue'))