def create_artists(self, legend, orig_handle, x0, y0, width, height, fontsize, trans): l1 = plt.Line2D([x0, y0 + width], [0.7 * height, 0.7 * height], linestyle=orig_handle[0], color=orig_handle[1]) l2 = plt.Line2D([x0, y0 + width], [0.3 * height, 0.3 * height], linestyle=orig_handle[2], color=orig_handle[3]) return [l1, l2]
def button_press_callback(self, event): """Left button: add point; middle button: delete point; right button: fill polygon and stop interaction. """ if event.inaxes: x, y = event.xdata, event.ydata ax = event.inaxes if event.button == 1: # If you press the left button if self.line == None: # if there is no line, create a line self.line = plt.Line2D( [x, x], [y, y], marker='.', color=self.color) self.start_point = [x, y] self.previous_point = self.start_point ax.add_line(self.line) self.lines.append(self.line) self.xcoords = [] self.ycoords = [] self.fig.canvas.draw() # add a segment else: # if there is a line, create a segment self.line = plt.Line2D([self.previous_point[0], x], [self.previous_point[1], y], marker='.', color=self.color) self.previous_point = [x, y] event.inaxes.add_line(self.line) self.lines.append(self.line) self.fig.canvas.draw() self.xcoords.append(x) self.ycoords.append(y) elif event.button == 2 and self.line != None: # middle button: remove last segment self.lines.pop(-1).remove() self.xcoords.pop() self.ycoords.pop() if len(self.lines) == 0: self.line = None return self.previous_point = self.xcoords[-1], self.ycoords[-1] self.line = self.lines[-1] elif event.button == 3 and self.line != None: # right button: close the loop self.line.set_data([self.previous_point[0], self.start_point[0]], [self.previous_point[1], self.start_point[1]]) ax.add_line(self.line) self.lines.append(self.line) self.line = None self.patch = ax.fill(self.xcoords, self.ycoords, alpha=0)[0] self.disconnect() self.fig.canvas.draw() if self.completion_callback is not None: self.completion_callback() else: pass # do not respond to any other types of key presses
def legend_outside_from_dicts(marker_dict, color_dict, marker_label_prepend='', color_label_prepend='', ax=None, bbox_to_anchor=(0.5, -.07), loc='upper center', ncol=None, label_cmp=None, marker_color='k'): marker_handles = [] marker_labels = [] for label in sorted(marker_dict.keys(), cmp=int_cmp): marker = marker_dict[label] handle = pylab.Line2D([], [], color=marker_color, marker=marker, linewidth=0) marker_handles.append(handle) marker_labels.append(marker_label_prepend + label) color_handles = [] color_labels = [] for label in sorted(color_dict.keys(), cmp=int_cmp): color = color_dict[label] handle = pylab.Line2D([], [], color=color, linewidth=3) color_handles.append(handle) color_labels.append(color_label_prepend + label) num_marker_handles = len(marker_handles) num_color_handles = len(color_handles) num_to_add = abs(num_marker_handles - num_color_handles) if num_marker_handles < num_color_handles: add_to_handles = marker_handles add_to_labels = marker_labels else: add_to_handles = color_handles add_to_labels = color_labels for add_idx in range(num_to_add): add_to_handles.append(pylab.Line2D([], [], color=None, linewidth=0)) add_to_labels.append('') handles = gu.roundrobin(marker_handles, color_handles) labels = gu.roundrobin(marker_labels, color_labels) if ax is None: ax = pylab.gca() if ncol is None: ncol = max(num_marker_handles, num_color_handles) lgd = ax.legend(handles, labels, loc=loc, ncol=ncol, bbox_to_anchor=bbox_to_anchor, prop={"size": 14}) return
def button_press_callback(self, event): if event.inaxes: x, y = event.xdata, event.ydata if event.button == 1: inside = self.inside_rois(x, y) if inside: idx = max(inside) self.rois[idx].selected = not self.rois[idx].selected self.draw_rois() self.previous_point = [x, y] else: self.points.append([x, y]) if self.line == None: self.line = pl.Line2D([x, x], [y, y], marker='o') self.start_point = [x, y] self.previous_point = self.start_point self.imax.add_line(self.line) else: self.line = pl.Line2D([self.previous_point[0], x], [self.previous_point[1], y], marker='o') self.previous_point = [x, y] self.imax.add_line(self.line) elif event.button == 3: if self.line != None: if len(self.points) > 2: self.line.set_data( [self.previous_point[0], self.start_point[0]], [self.previous_point[1], self.start_point[1]]) self.imax.add_line(self.line) roi = Point(self.new_id(), self.points) self.rois.append(roi) self.exported = False self.points = [] self.line = None self.draw_rois() elif self.line is None: inside = self.inside_rois(x, y) if inside: del self.rois[max(inside)] self.exported = False self.draw_rois() self.fig.canvas.draw()
def scale_image(label, max): fig, ax = plt.subplots(figsize=(5, 5)) # 画像サイズ fig.set_figheight(1) # 高さ調整 plt.xlim(0, max) plt.xlabel(label, fontsize=12) ax.set_frame_on(False) ax.get_xaxis().tick_bottom() ax.axes.get_yaxis().set_visible(False) ax.tick_params(direction='inout', length=10, labelsize=10) xmin, xmax = ax.get_xaxis().get_view_interval() ymin, ymax = ax.get_yaxis().get_view_interval() ax.add_artist( pylab.Line2D((xmin, xmax), (ymin, ymin), color='black', linewidth=2)) ax.text(max, -0.05, round(max, 2), fontsize=10) plt.tight_layout() #plt.show() plt.savefig(path + '/scale_' + label + '.png') plt.close()
def plot_states_3d(self, states, actions, model): states = np.array(states) COLORS = ['blue', 'm', 'orange'] ACTIONS = ['Buy', 'Sell', 'Do Nothing'] pca3d = PCA(n_components=3) reduced_3d = pca3d.fit_transform(states) print('PCA Full variance ratio: {}'.format( pca3d.explained_variance_ratio_.cumsum())) fig = pylab.figure() ax = Axes3D(fig) colors = map(lambda x: COLORS[int(x)], actions) ax.scatter(reduced_3d[:, 0], reduced_3d[:, 1], reduced_3d[:, 2], c=colors) legend_elements = [ pylab.Line2D([0], [0], color=COLORS[i], lw=4, label=action) for i, action in enumerate(ACTIONS) ] plt.legend(handles=legend_elements, loc='best') plt.title('States in reduced 3d with actions') self.save_figure(model, 'States in reduced 3d state with actions') plt.show()
def motion_notify_callback(self, event): """Draw a line from the last selected point to current pointer position. If left button is held, add points to the coords list at each movement. """ if time.time() - self.ts_draw < 0.1: return else: self.ts_draw = time.time() if event.inaxes: ax = event.inaxes x, y = event.xdata, event.ydata if event.button == None and self.line != None: # Move line around self.line.set_data([self.previous_point[0], x], [self.previous_point[1], y]) self.fig.canvas.draw() elif event.button == 1: # Free Hand Drawing line = plt.Line2D([self.previous_point[0], x], [self.previous_point[1], y]) ax.add_line(line) self.lines.append(line) self.previous_point = [x, y] self.fig.canvas.draw() self.xcoords.append(x) self.ycoords.append(y)
def plot_label_atlas(niimgs, labels, cut_coords=None, title=None): slicer = plot_bg(cut_coords, title) n_maps = len(niimgs) data = np.array([niimg.get_data() for niimg in niimgs]) affine = niimgs[0].get_affine() mask = np.any(data, axis=0) atlas = np.zeros(mask.shape, dtype='int') # atlas[mask] = np.argmax(np.abs(data), axis=0)[mask] atlas[mask] = np.argmax(data, axis=0)[mask] + 1 colors = (np.arange(n_maps) + 1) / float(n_maps) colors = np.hstack([colors, [0]]) slicer.plot_map(np.ma.masked_equal(colors[atlas], 0), affine, cmap=pl.cm.spectral, ) legend_lines = [pl.Line2D([0, 0], [0, 0], color=pl.cm.spectral(color), linewidth=4) for color in colors] ax = slicer.axes['z'].ax.get_figure().add_axes([.80, .1, .15, .8]) pl.axis('off') ax.legend(legend_lines, labels, loc='center right', prop=dict(size=4), title='Labels', borderaxespad=0, bbox_to_anchor=(1 / .85, .5)) return nb.Nifti1Image(atlas, affine=affine)
def __init__(self, x=[], y=[], beta=None, ax=None, **gridgen_options): if isinstance(x, str): x, y, beta = load(x) if ax is None: ax = pl.gca() self._ax = ax # Set default gridgen option, and copy over specified options. self.gridgen_options = {'ul_idx': 0, 'shp': (32, 32), 'verbose': True} for key, value in gridgen_options.iteritems(): self.gridgen_options[key] = gridgen_options[key] x = list(x); y = list(y) assert len(x)==len(y), 'arrays must be equal length' if beta is None: self.beta = [0 for xi in x] else: assert len(x)==len(beta), 'beta must have same length as x and y' self.beta = list(beta) self._line = pl.Line2D(x, y, marker='o', markerfacecolor='orange', animated=True) self._ax.add_line(self._line) self._canvas = self._line.figure.canvas self._key_id = self._ax.figure.canvas.mpl_connect('key_press_event', self._on_return) self._click_id = self._ax.figure.canvas.mpl_connect('button_press_event', self._on_click) if len(x) > 0: self._init_boundary_interactor()
def plotGridOf2DsWithColor(features, pairs, colors, markerShapes, plotName, fileTypeSuffix, alphaValue, size, offSetMulti): if len(features.ix[:,0].unique() ) != len(colors): print ("Numer of colors=", len(colors), "\tNumber of unique features=", len(features.ix[:,0].unique() ) ) print ("\nNumber of colors does not correspond to number of unique label values. Please fix!") return np_pairs = np.array(pairs) for i in range(np_pairs.shape[0]): print("Plot", i , pairs[i]) xUnique = len(features[pairs[i][0]].unique() )*1.0 yUnique = len(features[pairs[i][1]].unique() )*1.0 labelsUnique = features.ix[:,0].unique().tolist() plt.subplot(math.ceil(math.sqrt(np_pairs.shape[0]) ), math.ceil(math.sqrt(np_pairs.shape[0]) ), i+1) # This is setting the subplot grid plt.xlabel(np_pairs[i][0]) plt.ylabel(np_pairs[i][1]) # dfList is a list of dataframes of the columns in the "pairs" to be plotted, where each dataframe has a unique features in the predictive feature (Survived for Titanic dataset). dfList = [] for label in features.ix[:,0].unique(): dfList.append(features.loc[ features.ix[:,0] == label, [ pairs[i][0], pairs[i][1] ] ] ) emptyTuple = () lineTuple = list(emptyTuple) lineNameTuple = list(emptyTuple) for ite in range(len(dfList) ): # Offsets are for having part of the point being able to be seen around the point itself. By dividing by unique values, it makes this do nothing for continuous variables xOffSet = .05 * math.cos(2*math.pi/ (1.0 * (1+ite) * len(labelsUnique) ) ) / xUnique yOffSet = .05 * math.sin(2*math.pi/ (1.0 * (1+ite) * len(labelsUnique) ) ) / yUnique legendLabel = features.columns[0] + '=' + str(labelsUnique[ite] ) plt.scatter(dfList[ite].ix[:,0] + xOffSet*offSetMulti, dfList[ite].ix[:,1] + yOffSet*offSetMulti, color = colors[ite], marker=markerShapes[ite], alpha=alphaValue, s=size, label=legendLabel)#s=110 # The rest of the for loop is for mamking the legend. It's complicated because it's difficult to get the alpha of a scatterplot different on the legend. Had to make lines to do it. globals()['line%s' % ite] = pylab.Line2D( range(1), range(1), color='white', marker=markerShapes[ite], markersize=4, markerfacecolor=colors[ite], alpha=1) lineTuple.append(globals()['line%s' % ite] ) lineNameTuple.append(legendLabel) plt.grid(True) leg = plt.legend(tuple(lineTuple), tuple(lineNameTuple), bbox_to_anchor=(0, 0), loc=0, fontsize=8) plt.savefig(plotName, format=fileTypeSuffix) plt.show()
def draw_limited_plane(plane: LimitedSurface, color="blue", alpha=0.5): surface = plane.surface if not isinstance(surface, Plane): return norm = surface.norm_vec(point=[]) const = np.dot(surface.rad, norm) limits = plane.limits # keep the unique values x = {-(const + limits[1][i] * norm[1]) / norm[0] for i in range(2)} y = {-(const + limits[0][i] * norm[0]) / norm[1] for i in range(2)} x.update(limits[0]) y.update(limits[1]) x = list(x) y = list(y) line = None belong_points = set() for k in range(len(x)): for l in range(len(y)): point = (x[k], y[l]) if surface.is_point_belong(point) and plane._is_point_in_limits( point): belong_points.add(point) belong_points = list(belong_points) if len(belong_points) == 2: line = pylab.Line2D([belong_points[i][0] for i in range(2)], [belong_points[i][1] for i in range(2)]) pylab.gca().add_line(line) return
def plot_contour_atlas(niimgs, labels, cut_coords=None, title=None, percentile=99): legend_lines = [] slicer = plot_bg(cut_coords, title) atlas = np.vstack([niimg.get_data()[np.newaxis] for niimg in niimgs]) # atlas = StandardScaler().fit_transform(atlas.T).T affine = niimgs[0].get_affine() for i, (label, data) in enumerate(zip(labels, atlas)): data = np.array(_smooth_array(data, affine, 5), copy=True) data[data < 0] = 0 color = np.array(pl.cm.Set1(float(i) / (len(labels) - 1))) # data, affine = niimg.get_data(), niimg.get_affine() # affine = niimg.get_affine() level = scoreatpercentile(data.ravel(), percentile) slicer.contour_map(data, affine, levels=(level, ), linewidth=2.5, colors=(color, )) slicer.plot_map(data, affine, threshold=level, cmap=alpha_cmap(color)) legend_lines.append(pl.Line2D([0, 0], [0, 0], color=color, linewidth=4)) ax = slicer.axes['z'].ax.get_figure().add_axes([.80, .1, .15, .8]) pl.axis('off') ax.legend(legend_lines, labels, loc='center right', prop=dict(size=4), title='Labels', borderaxespad=0, bbox_to_anchor=(1 / .85, .5)) atlas = np.rollaxis(atlas, 0, 4) return nb.Nifti1Image(atlas, affine=affine)
def draw_car(ax, s, car_length=car_length, **kwargs): # parse the state x, y, alpha, speed, theta = s # rotation matrix for the car relative to the current universe dx, dy = cos(alpha), sin(alpha) R = array([(dx, -dy), (dy, dx)]) assert linalg.det(R) > 0. # scale the coordinate system so that the car's length is 1 R *= car_length # rotation matrix of the wheels relative to the car Rwheel = array([(cos(theta), -sin(theta)), (sin(theta), cos(theta))]) # rotation matrix of the wheels relative to the current universe Rwheel = dot(R, Rwheel) # body of the car in the curernt universe body = dot([(-2, -1), (2, -1), (2, 1), (-2, 1)], R.T) + (x, y) # the front axle, in the current universe axle = dot([(2, -1.5), (2, 1.5)], R.T) + (x, y) # a wheel. a vertical segment in its own coordinate system wheel = dot([(-.5, 0), (.5, 0)], Rwheel.T) hbody = P.Polygon(body, fill=False, edgecolor=kwargs.get('color', 'b')) haxle = P.Line2D(axle[:, 0], axle[:, 1], **kwargs) hleftwheel = P.Line2D([axle[0, 0] + wheel[:, 0]], [axle[0, 1] + wheel[:, 1]], **kwargs) hrightwheel = P.Line2D([axle[1, 0] + wheel[:, 0]], [axle[1, 1] + wheel[:, 1]], **kwargs) hcenter = P.Line2D([x], [y], marker='o', ms=5, mec=None, **kwargs) # the artists for the car hs = (hbody, haxle, hleftwheel, hrightwheel, hcenter) # add artists to the axis if supplied if ax: for h in hs: ax.add_artist(h) return hs
def scatter_metroes(ax, data, color_pallete, **kargs): ''' Shows metro on axes ''' ax.scatter(data.loc[:,'x'],data.loc[:,'y'], transform = ccrs.PlateCarree(), color = 'red', marker='$M$', s=30, linewidths=0.1, alpha=1, zorder=115, ) return [pylab.Line2D([0],[0],linewidth=0, marker="$M$" ,color='red', alpha=1.0,), kargs['dot_name'][kargs['ind']]]
def plot(self, axes, plt): logger.debug('Color Level: %i' % self.color) cl = plt.color(self.color) for i in range(self.num_vectors): begI = read_half(self.binaryfile) begJ = read_half(self.binaryfile) endI = read_half(self.binaryfile) endJ = read_half(self.binaryfile) logger.debug( 'Vector: %i\tbegI: %3i\tbegJ: %3i\tendI: %3i\tendJ: %3i' % (i + 1, begI, begJ, endI, endJ)) l = pylab.Line2D([begI, endI], [begJ, endJ], color=cl) axes.add_line(l)
def tsplot(self, xlabel="", ylabel="", title=""): pylab.cla() indices = np.argsort(self.scores)[::-1] colors = sns.color_palette("deep", len(indices)) legend = [] color_lines = [] for i in indices: sns.tsplot(np.array(self.y[i]), color=colors[i], legend=True) legend.append(self.legend[i]) color_lines.append(pylab.Line2D([], [], color=colors[i])) pylab.legend(color_lines, legend).draggable() pylab.xlabel(xlabel) pylab.ylabel(ylabel) pylab.title(title)
def draw_axicon2D(surfaces: list, axes, is_isosceles: bool = True): """ draw axicon :param surfaces: surfaces from method create_axicon() :param axes: pylab.gca() :param is_isosceles: :return: """ if not all([isinstance(i, LimitedSurface) for i in surfaces]): return False xy = [surfaces[0].limits[0][0], surfaces[0].limits[1][1]] l1 = pylab.Line2D([xy[0], 0], [xy[1], 0]) l2 = None l3 = None if is_isosceles: l2 = pylab.Line2D([xy[0], 0], [-xy[1], 0]) l3 = pylab.Line2D([xy[0], xy[0]], [xy[1], -xy[1]]) else: l3 = pylab.Line2D([xy[0], xy[0]], [xy[1], 0]) l2 = pylab.Line2D([xy[0], 0], [0, 0]) axes.add_line(l3) axes.add_line(l2) axes.add_line(l1)
def __init__(self, ax, oncreated=None, lineprops=None): AxesWidget.__init__(self, ax) self.oncreated = oncreated self.verts = None if lineprops is None: lineprops = dict() self.line = pl.Line2D([], [], **lineprops) self.line.set_visible(False) self.ax.add_line(self.line) self.connect_event('button_press_event', self.onpress) # self.connect_event('button_release_event', self.onrelease) self.connect_event('motion_notify_event', self.onmove)
def draw_plane(plane: Plane, color="blue", alpha=0.5): # matrix of rotation m = [[0, -1], [1, 0]] # direction vector r = np.dot(m, plane.norm_vec([])) # coords = vray.collect_point_to_draw(r,) point = [ ARay.calc_point_of_ray_(r, plane.rad, 10_000), ARay.calc_point_of_ray_(r, plane.rad, -10_000) ] line = pylab.Line2D([point[i][0] for i in range(2)], [point[i][1] for i in range(2)], color=color, alpha=alpha) pylab.gca().add_line(line)
def main(): dim = 16 corners, (edges0, edges1) = hypercubeCornersEdges(dim) baseRot = eye(dim) w = array([[1 for ii in range(dim)]]) w = random.random(dim) baseRot[0,:] = w print 'baseRot is\n', baseRot gramSchmidt(baseRot) print 'baseRot is\n', baseRot if linalg.det(baseRot) < 0: baseRot[-1,:] = -baseRot[-1,:] baseRot = baseRot.T #baseRot = eye(dim) deltaRot = rotationMatrix(dim, None, .01, skipFirst = True) rot = copy(baseRot) for iteration in xrange(2000): rot = dot(rot, deltaRot) cornersRot = dot(corners, rot) edges0Rot = dot(edges0, rot) edges1Rot = dot(edges1, rot) #pl.figure(0) pl.cla() #print 'corners:\n', corners #print 'cornersRot:\n', cornersRot pl.plot(cornersRot[:,0], cornersRot[:,1], 'ro') ax = pl.gca() for ii in range(edges0Rot.shape[0]): line = pl.Line2D([edges0Rot[ii,0], edges1Rot[ii,0]], [edges0Rot[ii,1], edges1Rot[ii,1]], linewidth = 1) ax.add_line(line) if iteration == 0: pl.axis('equal') pl.draw() axlim = looser(pl.axis(), .3) pl.axis(axlim) pl.draw() pl.savefig('rot_%02d_%05d.png' % (dim, iteration)) sleep(.001) raw_input('Enter to exit.')
def motion_notify_callback(self, event): if event.inaxes: x, y = event.xdata, event.ydata if event.button == None and self.line != None: self.line.set_data([self.previous_point[0], x], [self.previous_point[1], y]) elif event.button == 1: line = pl.Line2D([self.previous_point[0], x], [self.previous_point[1], y]) self.points.append([x, y]) self.imax.add_line(line) self.previous_point = [x, y] elif event.button == 3: pass self.update_sfig(x, y) self.fig.canvas.draw()
def drawLine (axes): """ Рисование линии """ x0 = 0 y0 = 0 x1 = 1 y1 = 0.5 x2 = 0.5 y2 = 1.0 line = pylab.Line2D ([x0, x1, x2], [y0, y1, y2], color="k") axes.add_line (line) pylab.text (0.5, 1.1, "Line2D", horizontalalignment="center")
def draw_ray(axes, way_points_of_ray: list, color="green"): if len(way_points_of_ray) == 2: axes.add_line( pylab.Line2D(way_points_of_ray[0], way_points_of_ray[1], color=color, marker='')) if len(way_points_of_ray) == 3: axes.plot(way_points_of_ray[0], way_points_of_ray[1], way_points_of_ray[2], label='LINE', color=color) axes.scatter(way_points_of_ray[0], way_points_of_ray[1], way_points_of_ray[2], c='b', marker='o')
def draw_ray_pool(pool: rays_pool.RaysPool, ray_const_length: float = 2, alpha: float = 1, color="green"): if pool.compon_index_class.DIM != 2: raise AttributeError("NON-two-dimensional ray pool") for i in range(len(pool)): if (pool.t1(i) != -1) and (pool.t1(i) is not None): t1 = pool.t1(i) else: t1 = ray_const_length coords = collect_point_to_draw(pool.e(i), pool.r(i), pool.t0(i), t1) line = pylab.Line2D(coords[0], coords[1], color=color, alpha=alpha) axes = pylab.gca() axes.add_line(line)
def __init__(self, *args, **kwargs): ax = kwargs.pop('ax', None) if ax is None: ax = pl.gca() self._ax = ax assert len( args ) <= 2, 'Input is either verticies (1 arg), or x and y (2 args)' if args is not (): if isinstance(args[0], str): verts = load(x) x, y = zip(*verts) x = list(x) y = list(y) elif len(args) == 1: # assume verticies input verts = args[0] x, y = zip(*verts) x = list(x) y = list(y) else: # x and y inputs x = list(args[0]) y = list(args[1]) assert len(x) == len(y), 'x and y must have the same length.' else: # no input x = [] y = [] self._line = pl.Line2D(x, y, marker='o', markerfacecolor='orange', animated=True) self._ax.add_line(self._line) self._canvas = self._line.figure.canvas self._key_id = self._ax.figure.canvas.mpl_connect( 'key_press_event', self._on_return) self._click_id = self._ax.figure.canvas.mpl_connect( 'button_press_event', self._on_click) if len(x) > 0: self._init_boundary_interactor()
def price_and_inventory_with_actions(self, states, actions, model): states = np.array(states) COLORS = ['blue', 'm', 'orange'] ACTIONS = ['Buy', 'Sell', 'Do Nothing'] colors = map(lambda x: COLORS[int(x)], actions) plt.scatter(states[:, 0], states[:, 3], c=colors) legend_elements = [ pylab.Line2D([0], [0], color=COLORS[i], lw=4, label=action) for i, action in enumerate(ACTIONS) ] plt.legend(handles=legend_elements, loc='best') plt.xlabel('Price') plt.ylabel('Inventory') plt.title('Price and inventory with actions') self.save_figure(model, 'States in 3d with actions 1') plt.show()
def create_artist(self): """ decides whether the artist should be visible or not in the current axis current_axis : names of x, y axis """ verts = self.coordinates if not self.tracky: trans = self.ax.get_xaxis_transform(which='grid') elif not self.trackx: trans = self.ax.get_yaxis_transform(which='grid') else: trans = self.ax.transData self.artist = pl.Line2D([verts[0]], [verts[1]], transform=trans, picker=15) self.update_looks('inactive') self.ax.add_artist(self.artist)
def scatter_plot_rewards_for_instances_last_iteration( self, actions, rewards, model): COLORS = ['blue', 'm', 'orange'] ACTIONS = ['Buy', 'Sell', 'Do Nothing'] colors = map(lambda x: COLORS[int(x)], actions) instances = range(len(actions)) plt.scatter(instances, rewards, c=colors, alpha=0.3, cmap='viridis') plt.grid(color='gray', linestyle='-', linewidth=0.25, alpha=0.5) legend_elements = [ pylab.Line2D([0], [0], color=COLORS[i], lw=4, label=action) for i, action in enumerate(ACTIONS) ] plt.legend(handles=legend_elements, loc='best') # plt.colorbar() # show color scale plt.title('Rewards for specific actions in the last iteration') plt.xlabel('Instance') plt.ylabel('Reward') self.save_figure(model, 'Scatter plot 1') plt.show()
def scatter(ax, data, color_pallete, **kargs): ''' Creates points on axes and a colorbar Parameters --------- ax : geoaxes axes in which points will be visialized data : DataFrame having [x,y] in columns color_pallete : dict {for what:hexcolor} see source Keyword arguments ----------------- do_colorbar : bool required If true then will show colorbar on axes ''' ax.scatter(data.loc[:,'x'],data.loc[:,'y'], transform = ccrs.PlateCarree(), color = color_pallete['points_in'], s=kargs['sc_size'], alpha=kargs['sc_alpha'], zorder=30, ) if kargs['do_colorbar'][kargs['ind']]==True: im = ax.imshow([[1,1,1,1],[2,2,2,2]], interpolation='nearest', cmap=kargs['cm'],vmin=0, vmax=1) N = kargs['max_val'] rnd = -(len(str(int(N/2)))-1) print(N,rnd,[0,int(round(N/2,rnd)),int(round(N,rnd))]) cax = kargs['fig'].add_axes([0.75, 0.20, 0.02, 0.2]) cbar = kargs['fig'].colorbar(im, cax=cax, ticks=[0,0.5,1]) cax.yaxis.set_ticks_position('left') yticks = cbar.ax.set_yticklabels( [0,str(int(round(N/2,rnd))),int(round(N,rnd))]) cbar.ax.tick_params(axis="y",labelsize=9) for tick in yticks: tick.set_color(color_pallete['points_in']) return [pylab.Line2D([0],[0],linewidth=0, marker="o" ,color=color_pallete['points_in'], alpha=1.0,), kargs['dot_name'][kargs['ind']]]
def plot_circle_data1(offset): (center_circle, ring_touching, ring_near, ring_far, near_distance, far_distance, angles) = circle_data1(offset) def get_params(obj): x, y = obj.cshape.center return obj.name, x, y, obj.cshape.r import pylab fig = pylab.figure(figsize=(6.0, 6.0)) # size in inches fig.suptitle('circle_data1', fontsize=12) pylab.axes().set_aspect('equal') # aspect ratio name, x, y, r = get_params(center_circle) cir = pylab.Circle((x, y), radius=r, ec='black', fc='none') pylab.gca().add_patch(cir) xmax = r for ring, color in [(ring_touching, 'r'), (ring_near, 'g'), (ring_far, 'b')]: for obj in ring: name, x, y, r = get_params(obj) cir = pylab.Circle((x, y), radius=r, ec=color, fc='none') pylab.gca().add_patch(cir) ymin = -(xmax + (2 * r + far_distance) * 3) xmax = xmax + (2 * r + far_distance) * 2 # axis: xmin, xmax, ymin, ymax pylab.axis([-xmax, xmax, ymin, xmax]) # make legends labels = ['center_circle', 'overlapping ring', 'near ring', 'far ring'] colors = ['black', 'r', 'g', 'b'] dummys = [pylab.Line2D([0, 1], [0, 1], lw=2.0, c=e) for e in colors] pylab.gca().legend(dummys, labels, ncol=2, loc='lower center') # pylab.show() pylab.savefig('circle1_data.png')