我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用matplotlib.lines.Line2D()。
def draw_legend(data, da, lyr): """ Draw a point in the box Parameters ---------- data : dataframe params : dict lyr : layer Returns ------- out : DrawingArea """ key = mlines.Line2D([0.5*da.width], [0.5*da.height], alpha=data['alpha'], marker='o', markersize=da.width/2, markerfacecolor=data['fill'], markeredgecolor=data['color']) da.add_artist(key) return da
def test_generate_plot_lines(): colordict = { 'cat1': '#001122', 'cat2': '#112233', 'cat3': '#223344', } styledict = { 'cat1': '-', 'cat2': '--', 'cat3': '-', } plot_lines = generate_plot_lines(colordict, lambda x: 'Cat {}'.format(x), styledict) assert len(plot_lines) == 3 for line in plot_lines: assert type(line) == mlines.Line2D assert 'Cat ' in line._label assert '-' in line._linestyle if line._label == 'Cat 2': assert line._linestyle == '--'
def create_time_line(self, axes, t, y, time_value, label): """ creates a vertical line in the diagram, reaching from the x-axis to the plot at a given time t :param axes: :param t: :param y: :param time_value: :param label: :returns new counter value """ # don't create lines on the very left if time_value == t[-1]: return # create timeLine time_line = Line2D([time_value, time_value], [np.min(y), y[t.index(time_value)]], ls=self.line_style, c=self.line_color) axes.add_line(time_line) axes.text(time_value + self.spacing, self.label_posistions[self.label_counter], label, size=self.font_size)
def draw_legend(self, legend_ax): # Make a legend with proxy artists xpos_artist = lines.Line2D([],[], color='orange') ypos_artist = lines.Line2D([],[], color='limegreen') numpts_artist = lines.Line2D([],[], color='purple', linewidth=1) frozen_artist = patches.Rectangle((0,0), 1, 1, fc='lightblue', ec='None') missing_artist = patches.Rectangle((0,0), 1, 1, fc='yellow', ec='None') lost_artist = patches.Rectangle((0,0), 1, 1, fc='red', ec='None') # Place it in center of top "subplot" area legend_ax.legend( [xpos_artist, ypos_artist, numpts_artist, frozen_artist, missing_artist, lost_artist], ['x-pos', 'y-pos', '# Detection pts', 'Frozen', 'Missing', 'Lost'], loc='center', fontsize=12, ncol=4, ) legend_ax.axis('off') format_axis(legend_ax)
def create_dummy_line(**kwds): return Line2D([], [], **kwds)
def draw_element(ax,el,**kwargs): coords = np.array([nd.coord for nd in el.nodes]) line = Line2D(coords[:,0],coords[:,1],**kwargs) line2 = Line2D((coords[:,0][-1],coords[:,0][0]),(coords[:,1][-1],coords[:,1][0]),**kwargs) ax.add_line(line) ax.add_line(line2)
def draw_element_disp(ax,el,factor = 1.,ls = "dashed",**kwargs): coord = np.array([nd.coord for nd in el.nodes]) n = len(coord) disp = np.array([nd.disp[key] for nd in el.nodes for key in ["Ux","Uy"]]) disp = disp.reshape(n,2) new_coords = coord+disp*factor*1e3 line = Line2D(new_coords[:,0],new_coords[:,1],linestyle = ls,**kwargs) line2 = Line2D((new_coords[:,0][-1],new_coords[:,0][0]),(new_coords[:,1][-1],new_coords[:,1][0]),ls = ls,**kwargs) ax.add_line(line) ax.add_line(line2)
def draw_legend(data, da, lyr): """ Draw a rectangle with a horizontal strike in the box Parameters ---------- data : dataframe da : DrawingArea lyr : layer Returns ------- out : DrawingArea """ data['size'] *= SIZE_FACTOR # background facecolor = to_rgba(data['fill'], data['alpha']) if facecolor is None: facecolor = 'none' bg = Rectangle((da.width*.125, da.height*.25), width=da.width*.75, height=da.height*.5, linewidth=data['size'], facecolor=facecolor, edgecolor=data['color'], linestyle=data['linetype'], capstyle='projecting', antialiased=False) da.add_artist(bg) strike = mlines.Line2D([da.width*.125, da.width*.875], [da.height*.5, da.height*.5], linestyle=data['linetype'], linewidth=data['size'], color=data['color']) da.add_artist(strike) return da
def draw_legend(data, da, lyr): """ Draw a vertical line in the box Parameters ---------- data : dataframe da : DrawingArea lyr : layer Returns ------- out : DrawingArea """ x = [0.5 * da.width] * 2 y = [0, da.height] data['size'] *= SIZE_FACTOR key = mlines.Line2D(x, y, alpha=data['alpha'], linestyle=data['linetype'], linewidth=data['size'], color=data['color'], solid_capstyle='butt', antialiased=False) da.add_artist(key) return da
def draw_legend(data, da, lyr): """ Draw a horizontal line in the box Parameters ---------- data : dataframe da : DrawingArea lyr : layer Returns ------- out : DrawingArea """ data['size'] *= SIZE_FACTOR x = [0, da.width] y = [0.5 * da.height] * 2 key = mlines.Line2D(x, y, alpha=data['alpha'], linestyle=data['linetype'], linewidth=data['size'], color=data['color'], solid_capstyle='butt', antialiased=False) da.add_artist(key) return da
def draw_legend(data, da, lyr): """ Draw a point in the box Parameters ---------- data : dataframe params : dict lyr : layer Returns ------- out : DrawingArea """ if data['fill'] is None: data['fill'] = data['color'] size = (data['size']+data['stroke'])*SIZE_FACTOR stroke = data['stroke'] * SIZE_FACTOR key = mlines.Line2D([0.5*da.width], [0.5*da.height], alpha=data['alpha'], marker=data['shape'], markersize=size, markerfacecolor=data['fill'], markeredgecolor=data['color'], markeredgewidth=stroke) da.add_artist(key) return da
def generate_plot_lines(colordict, label_fcn, styledict): plot_lines = [] # plot_labs = [] for cat_val in sorted(colordict.keys()): # http://matplotlib.org/users/legend_guide.html lin = mlines.Line2D( xdata=[], ydata=[], linestyle=styledict[cat_val], color=colordict[cat_val], label=label_fcn(cat_val) ) plot_lines.append(lin) # plot_labs.append(mt) return plot_lines
def fooCandlestick(ax, quotes, width=0.5, colorup='#FFA500', colordown='#222', alpha=1.0): OFFSET = width/2.0 lines = [] boxes = [] for q in quotes: timestamp, op, hi, lo, close = q[:5] box_h = max(op, close) box_l = min(op, close) height = box_h - box_l if close>=op: color = '#3fd624' else: color = '#e83e2c' vline_lo = Line2D( xdata=(timestamp, timestamp), ydata=(lo, box_l), color = 'k', linewidth=0.5, antialiased=True, zorder=10 ) vline_hi = Line2D( xdata=(timestamp, timestamp), ydata=(box_h, hi), color = 'k', linewidth=0.5, antialiased=True, zorder=10 ) rect = Rectangle( xy = (timestamp-OFFSET, box_l), width = width, height = height, facecolor = color, edgecolor = color, zorder=10) rect.set_alpha(alpha) lines.append(vline_lo) lines.append(vline_hi) boxes.append(rect) ax.add_line(vline_lo) ax.add_line(vline_hi) ax.add_patch(rect) ax.autoscale_view() return lines, boxes # Enable a Grid
def line2d(x, y, ax, **kwargs): """plot a 2d line between (x1, y1) and (x2, y2)""" line = Line2D(x, y, linewidth=1, color='k', **kwargs) ax.add_line(line)
def createTimeLine(self, axes, t, y, time_value, label): if time_value != t[-1]: # create timeLine timeLine = Line2D([time_value, time_value], \ [axes.get_ylim()[0], y[t.index(time_value)]], \ ls=self.line_style, \ c=self.line_color) axes.add_line(timeLine) # create label axes.text(time_value + self.spacing, self.posLabel[self.counter], label, size=self.font_size) self.counter = self.counter + 1
def create_time_line(self, axes, t, y, time_value, label): if time_value != t[-1]: time_line = Line([time_value, time_value], [np.min(y), y[np.where(t == time_value)][0]], linewidth=self.line_width, ls=self.line_style, c=self.line_color) axes.add_line(time_line) axes.text(time_value + self.spacing, self.label_positions[self.counter], label, color=self.font_color, size=self.font_size) self.counter += 1
def __init__(self, visuals): self.visuals = visuals if visuals: self.train_loss_list = [] self.val_loss_list = [] self.val_kappa_list = [] self.val_accu_list = [] self.epoch_list = [] plt.ion() self.f, self.ax = plt.subplots(3, 1) red_line = mlines.Line2D([], [], color='red', markersize=15, label='Training loss') green_line = mlines.Line2D([], [], color='green', markersize=15, label='Validation loss') self.ax[0].legend(handles=[red_line, green_line], prop={'size': 8}) store_training_logs.delete_file('run_script_logs.pkl')
def __init__(self, visuals): self.visuals = visuals if visuals: self.train_loss_list = [] self.val_loss_list = [] self.val_kappa_list = [] self.val_accu_list = [] self.epoch_list = [] plt.ion() self.f, self.ax = plt.subplots(3, 1) self.f.subplots_adjust(hspace=.7) red_line = mlines.Line2D([], [], color='red', markersize=15, label='Training loss') green_line = mlines.Line2D([], [], color='green', markersize=15, label='Validation loss') self.ax[0].legend(handles=[red_line, green_line], prop={'size': 8}) store_training_logs.delete_file('run_script_logs.pkl')
def example_naivehierarchicalclustering(): """Naive hierarchical clustering algorithm using DTW and based on . For a more efficient approach, check: Mueen, A and Keogh, E, Extracting Optimal Performance from Dynamic Time Warping, Tutorial, KDD 2016 http://www.cs.unm.edu/~mueen/DTW.pdf :return: None """ series = [ np.array([0.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0]), np.array([0.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0]), np.array([2.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]), np.array([2.0, 1.0, 1.0, 0.0, 0.0, 2.0, 3.0]), np.array([4.0, 2.0, 1.0, 0.0, 0.0, 1.0, 3.0]) ] dists = dtw.distance_matrix_fast(series) print("Distance matrix:\n{}".format(dists)) dists_cond = np.zeros(size_cond(len(series))) idx = 0 for r in range(len(series)-1): dists_cond[idx:idx+len(series)-r-1] = dists[r, r+1:] idx += len(series)-r-1 z = linkage(dists_cond, method='complete', metric='euclidean') print(z) fig, axes = plt.subplots(2, 1, figsize=(8, 3)) for idx, serie in enumerate(series): serie += idx * 0.1 axes[0].plot(serie, label=str(idx)) axes[0].text(0 + 0.15 * (-1)**idx * idx, serie[0] + 0.15 * idx, idx) axes[0].add_line(Line2D([0, 0 + 0.15 * (-1)**idx * idx], [serie[0], serie[0] + 0.15 * idx], linewidth=1, color='gray')) axes[0].legend(loc=1) dendrogram(z, ax=axes[1]) plt.show(block=True)
def create_proxy(c): line = Line2D([0],[0],color=c,marker='s',linestyle='None') return line
def add_mapping(patches, colors, start_ratio, patch_size, ind_bgn, top_left_list, loc_diff_list, num_show_list, size_list): start_loc = top_left_list[ind_bgn] \ + (num_show_list[ind_bgn] - 1) * np.array(loc_diff_list[ind_bgn]) \ + np.array([start_ratio[0] * size_list[ind_bgn], -start_ratio[1] * size_list[ind_bgn]]) end_loc = top_left_list[ind_bgn + 1] \ + (num_show_list[ind_bgn + 1] - 1) \ * np.array(loc_diff_list[ind_bgn + 1]) \ + np.array([(start_ratio[0] + .5 * patch_size / size_list[ind_bgn]) * size_list[ind_bgn + 1], -(start_ratio[1] - .5 * patch_size / size_list[ind_bgn]) * size_list[ind_bgn + 1]]) patches.append(Rectangle(start_loc, patch_size, patch_size)) colors.append(Dark) patches.append(Line2D([start_loc[0], end_loc[0]], [start_loc[1], end_loc[1]])) colors.append(Black) patches.append(Line2D([start_loc[0] + patch_size, end_loc[0]], [start_loc[1], end_loc[1]])) colors.append(Black) patches.append(Line2D([start_loc[0], end_loc[0]], [start_loc[1] + patch_size, end_loc[1]])) colors.append(Black) patches.append(Line2D([start_loc[0] + patch_size, end_loc[0]], [start_loc[1] + patch_size, end_loc[1]])) colors.append(Black)
def __init__(self,init,**kwargs): lines.Line2D.__init__(self,[],[],**kwargs) self.xdata = np.array([0,1/5.0,2/5.,3/5.,4/5.,1])+init self.ydata = np.array([0,0,0.05,-0.05,0,0]) # Set data self.set_xdata(self.xdata) self.set_ydata(self.ydata) #self.set_linestyle("-") #Solid line
def _config_axes(self, X, Y): ''' Make an axes patch and outline. ''' ax = self.ax ax.set_frame_on(False) ax.set_navigate(False) xy = self._outline(X, Y) ax.update_datalim(xy) ax.set_xlim(*ax.dataLim.intervalx) ax.set_ylim(*ax.dataLim.intervaly) if self.outline is not None: self.outline.remove() self.outline = lines.Line2D( xy[:, 0], xy[:, 1], color=mpl.rcParams['axes.edgecolor'], linewidth=mpl.rcParams['axes.linewidth']) ax.add_artist(self.outline) self.outline.set_clip_box(None) self.outline.set_clip_path(None) c = mpl.rcParams['axes.facecolor'] if self.patch is not None: self.patch.remove() self.patch = mpatches.Polygon(xy, edgecolor=c, facecolor=c, linewidth=0.01, zorder=-1) ax.add_artist(self.patch) self.update_ticks()
def drawgreatcircle(self,lon1,lat1,lon2,lat2,del_s=100.,**kwargs): """ Draw a great circle on the map from the longitude-latitude pair ``lon1,lat1`` to ``lon2,lat2`` .. tabularcolumns:: |l|L| ============== ======================================================= Keyword Description ============== ======================================================= del_s points on great circle computed every del_s kilometers (default 100). \**kwargs other keyword arguments are passed on to :meth:`plot` method of Basemap instance. ============== ======================================================= .. note:: Cannot handle situations in which the great circle intersects the edge of the map projection domain, and then re-enters the domain. Returns a matplotlib.lines.Line2D object. """ # use great circle formula for a perfect sphere. gc = pyproj.Geod(a=self.rmajor,b=self.rminor) az12,az21,dist = gc.inv(lon1,lat1,lon2,lat2) npoints = int((dist+0.5*1000.*del_s)/(1000.*del_s)) lonlats = gc.npts(lon1,lat1,lon2,lat2,npoints) lons = [lon1]; lats = [lat1] for lon, lat in lonlats: lons.append(lon) lats.append(lat) lons.append(lon2); lats.append(lat2) x, y = self(lons, lats) return self.plot(x,y,**kwargs)
def factor_comparison(dfs, keys, figsize=(7,5)): compare = lookup(dfs, show_totals=True, keys=keys, exclude=['Solar', 'Wind']).fillna(0.) n_fueltypes, n_countries = compare.shape compare.columns.labels c= [tech_colors2[i] for i in compare.index.values[:-1]] + ['gold'] rcParams["axes.prop_cycle"] = cycler(color=c) #where both are zero, compare[compare.groupby(level=0, axis=1).transform(np.sum)<0.5]=np.nan fig, ax = plt.subplots(1,1, figsize=figsize) compare.T.plot(ax=ax, markevery=(0,2), style='o', markersize=5) compare.T.plot(ax=ax, markevery=(1,2), style='s', legend=None, markersize=4.5) lgd = ax.get_legend_handles_labels() for i,j in enumerate(compare.T.index.levels[0]): ax.plot(np.array([0,1])+(2*i), compare.T.loc[j]) indexhandles = [Line2D([0.4,.6],[.4,.6], marker=m, linewidth=0., markersize=msize, color='w', markeredgecolor='k', markeredgewidth=0.5) for m, msize in [['o', 5.], ['s', 4.5]]] indexlabels = ['Matched Dataset', 'ENTSOE Stats'] ax.add_artist(ax.legend(handles=indexhandles, labels=indexlabels)) ax.legend(handles= lgd[0][:len(c)], labels=lgd[1][:len(c)] ,title=False, loc=2) ax.set_xlim(-1,n_countries) ax.xaxis.grid(False) ax.set_xticks(np.linspace(0.5,n_countries-1.5,n_countries/2)) ax.set_xticklabels(compare.columns.levels[0].values, rotation=90) ax.set_xlabel('') ax.set_ylabel('Capacity [GW]') fig.tight_layout(pad=0.5)
def __init__(self, plotman): self.plotman = plotman self.axes = plotman.axes self.mode_colors = plotman.mode_colors # create a blank invariant violation polys self.inv_vio_polys = collections.PolyCollection([], animated=True, alpha=0.7, edgecolor='red', facecolor='red') self.axes.add_collection(self.inv_vio_polys) # create a blank currently-tracked set of states poly self.cur_state_line2d = Line2D([], [], animated=True, color='k', lw=2, mew=2, ms=5, fillstyle='none') self.axes.add_line(self.cur_state_line2d) self.parent_to_polys = OrderedDict() self.parent_to_markers = OrderedDict() self.waiting_list_mode_to_polys = OrderedDict() self.aggregation_mode_to_polys = OrderedDict() self.trace = collections.LineCollection( [[(0, 0)]], animated=True, colors=('k'), linewidths=(3), linestyle='dashed') self.axes.add_collection(self.trace) if plotman.settings.extra_lines is not None: lines = plotman.settings.extra_lines self.extra_lines_col = collections.LineCollection( lines, animated=True, colors=('gray'), linewidths=(2), linestyle='dashed') self.axes.add_collection(self.extra_lines_col) else: self.extra_lines_col = None self.freeze_attrs()
def add_reachable_poly(self, poly_verts, parent, mode_name): '''add a polygon which was reachable''' assert isinstance(parent, ContinuousPostParent) if len(poly_verts) <= 2: markers = self.parent_to_markers.get(parent) if markers is None: face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name) markers = Line2D([], [], animated=True, ls='None', alpha=0.5, marker='o', mew=2, ms=5, mec=edge_col, mfc=face_col) self.axes.add_line(markers) self.parent_to_markers[parent] = markers xdata = markers.get_xdata() ydata = markers.get_ydata() xdata.append(poly_verts[0][0]) ydata.append(poly_verts[0][1]) markers.set_xdata(xdata) markers.set_ydata(ydata) else: polys = self.parent_to_polys.get(parent) if polys is None: face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name) polys = collections.PolyCollection([], lw=2, animated=True, alpha=0.5, edgecolor=edge_col, facecolor=face_col) self.axes.add_collection(polys) self.parent_to_polys[parent] = polys paths = polys.get_paths() codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY] paths.append(Path(poly_verts, codes))
def add_mapping(patches, colors, start_ratio, end_ratio, patch_size, ind_bgn, top_left_list, loc_diff_list, num_show_list, size_list): start_loc = top_left_list[ind_bgn] \ + (num_show_list[ind_bgn] - 1) * np.array(loc_diff_list[ind_bgn]) \ + np.array([start_ratio[0] * (size_list[ind_bgn][1] - patch_size[1]), - start_ratio[1] * (size_list[ind_bgn][0] - patch_size[0])] ) end_loc = top_left_list[ind_bgn + 1] \ + (num_show_list[ind_bgn + 1] - 1) * np.array( loc_diff_list[ind_bgn + 1]) \ + np.array([end_ratio[0] * size_list[ind_bgn + 1][1], - end_ratio[1] * size_list[ind_bgn + 1][0]]) patches.append(Rectangle(start_loc, patch_size[1], -patch_size[0])) colors.append(Dark) patches.append(Line2D([start_loc[0], end_loc[0]], [start_loc[1], end_loc[1]])) colors.append(Darker) patches.append(Line2D([start_loc[0] + patch_size[1], end_loc[0]], [start_loc[1], end_loc[1]])) colors.append(Darker) patches.append(Line2D([start_loc[0], end_loc[0]], [start_loc[1] - patch_size[0], end_loc[1]])) colors.append(Darker) patches.append(Line2D([start_loc[0] + patch_size[1], end_loc[0]], [start_loc[1] - patch_size[0], end_loc[1]])) colors.append(Darker)
def redraw(self, origin, scale): for node in self.nodes: if isinstance(node, Annotation): node.xy = self.tr(node.xy, origin, scale) if hasattr(node, "xyann"): node.xyann = self.tr(node.xyann, origin, scale) elif isinstance(node, Line2D): newpos = self.tr(node.get_xydata(), origin, scale) node.set_xdata(newpos[:, 0]) node.set_ydata(newpos[:, 1]) else: raise TypeError("Don't know how to morph : %s" % node) self.origin = origin self.scale = scale
def plot_top_sims(cos_sim_mat,aids,N_recs,aid_counts,aid_dict, img_name = 'results\\Sample_similarities.png',threshold=0, main_name = None, var_name = 'Sim', plot_histograms=True): ''' Plot of anime with the highest similarity scores. ''' plt.figure(figsize=(6, 10)) f, axarr = plt.subplots(len(aids),N_recs+1) f.set_size_inches(6, 10) f.tight_layout() for (idx_0,aid) in enumerate(aids): image = get_image(aid_dict[aid]) axarr[idx_0,0].imshow(image) axarr[idx_0,0].axis("off") axarr[idx_0,0].set_title('Query ' + str(idx_0+1),size=10) top_aids,top_sims = get_highest_cos(cos_sim_mat,aid,aid_dict,N_recs,aid_counts,threshold) for (idx_1,aid_1) in enumerate(top_aids): image = get_image(aid_dict[aid_1]) if image != None: axarr[idx_0,idx_1+1].imshow(image) axarr[idx_0,idx_1+1].axis("off") axarr[idx_0,idx_1+1].set_title(var_name + ' = {:.2f}'.format(top_sims[idx_1]),size=10) # Add horizonatal lines: if not idx_0==0 or idx_0==len(aids): line = lines.Line2D((0,1),(1-1.0/len(aids)*idx_0*0.98,1-1.0/len(aids)*idx_0*0.98), transform=f.transFigure,color=[0,0,0]) f.lines.append(line) # TODO: the 0.98 shouldn't be necessary. Fixit. if main_name: plt.suptitle(main_name) #plt.savefig(img_name,dpi=300,format='png') plt.show() # Plot a histrogram of these similarities: if plot_histograms: for aid in aids: plt.hist(cos_sim_mat[aid,:]) plt.show() return None
def __init__(self, ax, x, y, col, parent): self.parent = parent self.removed = False self.x = x self.y = y _xlim = ax.get_xlim() _ylim = ax.get_ylim() self.line1 = Line2D(_xlim, (y,y), picker=5) self.line2 = Line2D((x,x), _ylim, picker=5) self.line1.set_color(col) self.line2.set_color(col) ax.add_line(self.line1) ax.add_line(self.line2) parent.signalGraphUpdate.emit()
def toggleCursor(self): print('toggleCursor') if self.cursorActive: inv = self.host.transData.inverted() _xlim = self.host.get_xlim() _ylim = self.host.get_ylim() _xy1 = self.host.transData.transform((_xlim[0],_ylim[1])) _xy2 = self.host.transData.transform((_xlim[1],_ylim[0])) #_xy1 = self.host.transData.transform((_posx[0],_posy[0])) #ä_xy2 = self.host.transData.transform((_posx[1],_posy[1])) _x1 = _xy1[0]+20 _x2 = _xy1[0]+40 _y1 = _xy2[1]+20 _y2 = _xy2[1]+40 _xy1t = inv.transform((_x1,_y1)) _xy2t = inv.transform((_x2,_y2)) self.cursorA = CursorStatic(self.host,_xy1t[0],_xy1t[1],'gray',self) self.cursorB = CursorStatic(self.host,_xy2t[0],_xy2t[1],'black',self) self.showCursorPos(self.cursorA.x,self.cursorA.y,'A') self.showCursorPos(self.cursorB.x,self.cursorB.y,'B') self.showCursorPos(math.fabs(self.cursorB.x-self.cursorA.x),math.fabs(self.cursorB.y-self.cursorA.y),'C') # # self.line = Line2D(_xy1,_xy2) # self.line1 = Line2D(_xlim, (_xy2t[1],_xy2t[1])) # self.line2 = Line2D((_xy1t[0],_xy1t[0]), _ylim) # self.host.add_line(self.line1) # self.host.add_line(self.line2) # self.signalGraphUpdate.emit() print ('cursor added') # self.cursorD = Cursor(self.host, useblit=False, color='blue', linewidth=2) else: self.cursorA.delLine() self.cursorA = None self.cursorB.delLine() self.cursorB = None
def __init__(self, points, line, linedata): if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "linkedview", "idpts": utils.get_id(points, suffix), "idline": utils.get_id(line), "data": linedata}
def _connection_line(x, fig, sourceax, targetax): """Helper function to connect time series and topolots""" from matplotlib.lines import Line2D transFigure = fig.transFigure.inverted() tf = fig.transFigure (xt, yt) = transFigure.transform(targetax.transAxes.transform([.5, .25])) (xs, _) = transFigure.transform(sourceax.transData.transform([x, 0])) (_, ys) = transFigure.transform(sourceax.transAxes.transform([0, 1])) return Line2D((xt, xs), (yt, ys), transform=tf, color='grey', linestyle='-', linewidth=1.5, alpha=.66, zorder=0)
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 draw_legend(data, da, lyr): """ Draw a rectangle in the box Parameters ---------- data : dataframe da : DrawingArea lyr : layer Returns ------- out : DrawingArea """ data['size'] *= SIZE_FACTOR # box facecolor = to_rgba(data['fill'], data['alpha']) if facecolor is None: facecolor = 'none' kwargs = dict( linestyle=data['linetype'], linewidth=data['size']) box = Rectangle((da.width*.125, da.height*.25), width=da.width*.75, height=da.height*.5, facecolor=facecolor, edgecolor=data['color'], capstyle='projecting', antialiased=False, **kwargs) da.add_artist(box) kwargs['solid_capstyle'] = 'butt' kwargs['color'] = data['color'] # middle strike through strike = mlines.Line2D([da.width*.125, da.width*.875], [da.height*.5, da.height*.5], **kwargs) da.add_artist(strike) # whiskers top = mlines.Line2D([da.width*.5, da.width*.5], [da.height*.75, da.height*.9], **kwargs) da.add_artist(top) bottom = mlines.Line2D([da.width*.5, da.width*.5], [da.height*.25, da.height*.1], **kwargs) da.add_artist(bottom) return da
def on_pick(self, event): artist = event.artist if not artist.get_visible(): return for idx, artist_set in enumerate(self.pick_sets): if artist in artist_set: self.pick_funs[idx](artist) return if isinstance(artist, Line2D): mevent = event.mouseevent # figure out if we picked marker or line self.drag_idx = self._get_idx_under_point(mevent) if self.drag_idx >= 0: # picked marker. ax = mevent.inaxes an, pt, _, _ = self.markers[self.drag_idx] an.set_visible(False) pt.set_visible(False) self.canvas.draw() self.markers[self.drag_idx][-1] = self.canvas.copy_from_bbox(ax.bbox) an.set_visible(True) pt.set_visible(True) ax.draw_artist(an) ax.draw_artist(pt) self.canvas.blit(ax.bbox) else: # save data to plot marker later mxval = mevent.xdata button = mevent.button if mxval is not None and button == 1 and not self.marker_line_info: self.marker_line_info = (artist, mxval, mevent.ydata, button, mevent.inaxes) elif isinstance(artist, Annotation): # delete marker. mevent = event.mouseevent if mevent.button == 3: targ_idx = None for idx, (an, pt, _, _) in enumerate(self.markers): if an is artist: targ_idx = idx break if targ_idx is not None: an, pt, _, _ = self.markers[targ_idx] del self.markers[targ_idx] an.set_visible(False) pt.set_visible(False) self.canvas.draw()
def _check_colors(self, collections, linecolors=None, facecolors=None, mapping=None): """ Check each artist has expected line colors and face colors Parameters ---------- collections : list-like list or collection of target artist linecolors : list-like which has the same length as collections list of expected line colors facecolors : list-like which has the same length as collections list of expected face colors mapping : Series Series used for color grouping key used for andrew_curves, parallel_coordinates, radviz test """ from matplotlib.lines import Line2D from matplotlib.collections import Collection, PolyCollection conv = self.colorconverter if linecolors is not None: if mapping is not None: linecolors = self._get_colors_mapped(mapping, linecolors) linecolors = linecolors[:len(collections)] self.assertEqual(len(collections), len(linecolors)) for patch, color in zip(collections, linecolors): if isinstance(patch, Line2D): result = patch.get_color() # Line2D may contains string color expression result = conv.to_rgba(result) elif isinstance(patch, PolyCollection): result = tuple(patch.get_edgecolor()[0]) else: result = patch.get_edgecolor() expected = conv.to_rgba(color) self.assertEqual(result, expected) if facecolors is not None: if mapping is not None: facecolors = self._get_colors_mapped(mapping, facecolors) facecolors = facecolors[:len(collections)] self.assertEqual(len(collections), len(facecolors)) for patch, color in zip(collections, facecolors): if isinstance(patch, Collection): # returned as list of np.array result = patch.get_facecolor()[0] else: result = patch.get_facecolor() if isinstance(result, np.ndarray): result = tuple(result) expected = conv.to_rgba(color) self.assertEqual(result, expected)
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 __init__(self): fig = plt.figure(figsize=(10,4)) a1_z = fig.add_subplot(1, 11, 1) a1_xy = fig.add_subplot(1, 11, (2, 6)) a2_z = fig.add_subplot(1, 11, 7) a2_xy = fig.add_subplot(1, 11, (8, 12)) plt.tight_layout() fig.suptitle("3D Sensor and Xbox Controller Demo", fontsize=18) plt.setp(a1_z.get_xticklabels(), visible=False) plt.setp(a2_z.get_xticklabels(), visible=False) a1_z.set_title('3D Sensor Z') a2_z.set_title('Xbox L Z') a1_xy.set_title('3D Sensor XY') a2_xy.set_title('Xbox L XY') # Joy 1 Z a1_z.set_ylabel('z') self.line_z1 = Line2D([], [], color='blue', linewidth=20) a1_z.add_line(self.line_z1) a1_z.set_xlim(-1, 1) a1_z.set_ylim(-1, 1) # Joy 1 XY a1_xy.set_xlabel('x') a1_xy.set_ylabel('y') self.line_xy1 = Line2D([], [], color='green', linewidth=3) a1_xy.add_line(self.line_xy1) a1_xy.set_xlim(-1, 1) a1_xy.set_ylim(-1, 1) # Joy 2 Z a2_z.set_ylabel('z') self.line_z2 = Line2D([], [], color='blue', linewidth=20) a2_z.add_line(self.line_z2) a2_z.set_xlim(-1, 1) a2_z.set_ylim(0, 1) # Joy 2 XY a2_xy.set_xlabel('x') a2_xy.set_ylabel('y') self.line_xy2 = Line2D([], [], color='green', linewidth=3) a2_xy.add_line(self.line_xy2) a2_xy.set_xlim(-1, 1) a2_xy.set_ylim(-1, 1) animation.TimedAnimation.__init__(self, fig, interval=50, blit=True)
def __init__(self): fig = plt.figure() ax1 = fig.add_subplot(1, 6, (1, 2)) ax2 = fig.add_subplot(1, 6, (3, 4)) ax3 = fig.add_subplot(1, 6, 5) self.t = np.linspace(0, 80, 400) self.x = np.cos(2 * np.pi * self.t / 10.) self.y = np.sin(2 * np.pi * self.t / 10.) self.z = 10 * self.t ax1.set_xlabel('x') ax1.set_ylabel('y') self.line1 = Line2D([], [], color='black') self.line1a = Line2D([], [], color='red', linewidth=2) self.line1e = Line2D( [], [], color='red', marker='o', markeredgecolor='r') ax1.add_line(self.line1) ax1.add_line(self.line1a) ax1.add_line(self.line1e) ax1.set_xlim(-1, 1) ax1.set_ylim(-2, 2) ax1.set_aspect('equal', 'datalim') ax2.set_xlabel('y') ax2.set_ylabel('z') self.line2 = Line2D([], [], color='black') self.line2a = Line2D([], [], color='red', linewidth=2) self.line2e = Line2D( [], [], color='red', marker='o', markeredgecolor='r') ax2.add_line(self.line2) ax2.add_line(self.line2a) ax2.add_line(self.line2e) ax2.set_xlim(-1, 1) ax2.set_ylim(0, 800) ax3.set_xlabel('x') ax3.set_ylabel('z') self.line3 = Line2D([], [], color='black') self.line3a = Line2D([], [], color='red', linewidth=2) self.line3e = Line2D( [], [], color='red', marker='o', markeredgecolor='r') ax3.add_line(self.line3) ax3.add_line(self.line3a) ax3.add_line(self.line3e) ax3.set_xlim(-1, 1) ax3.set_ylim(0, 800) animation.TimedAnimation.__init__(self, fig, interval=50, blit=True)
def plot_lambdas_parallel_coordinates(lambdas, relevance_scores, individual=False, cumulative=False): unique_scores = sorted(np.unique(relevance_scores).astype(int), reverse=True) colors = ['r', 'g', 'b', 'y', 'c', 'm', 'y', 'k'] if not individual: plt.figure() legend_handles = [] legend_labels = [] for c, r in enumerate(unique_scores): legend_handles.append(mlines.Line2D([], [], color=colors[c], linewidth=2)) legend_labels.append('Relevance %d' % r) if cumulative: lambdas_cumsum = lambdas.cumsum(axis=0) ymin, ymax = lambdas_cumsum.min(), lambdas_cumsum.max() else: ymin, ymax = lambdas.min(), lambdas.max() for c, r in enumerate(unique_scores): if individual: plt.figure() if cumulative: plt.plot(lambdas[:, relevance_scores == r].cumsum(axis=0), '-', marker='.', markersize=1, c=colors[c], alpha=0.4) else: plt.plot(lambdas[:, relevance_scores == r], '-', marker='.', markersize=1, c=colors[c], alpha=0.4) if individual: plt.gca().get_xaxis().set_major_locator(MaxNLocator(integer=True)) plt.gca().set_ylim([ymin, ymax]) plt.title('Paralell Coordinates for%sLambdas (Relevance %d)' % (' Cumulative ' if cumulative else ' ', r)) plt.xlabel('Trees') plt.ylabel('Cumulative Lambda Values' if cumulative else 'Lambda Values') plt.show() if not individual: plt.gca().get_yaxis().set_major_locator(MaxNLocator(integer=True)) plt.gca().set_ylim([ymin, ymax]) plt.title('Paralell Coordinates for%sLambdas (Relevance %d)' % (' Cumulative ' if cumulative else ' ', r)) plt.xlabel('Trees') plt.ylabel('Cumulative Lambda Values' if cumulative else 'Lambda Values') plt.legend(legend_handles, legend_labels, loc='best') plt.show()
def barplot(bars, title='', upColor='blue', downColor='red'): """ Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects. """ import pandas as pd import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Rectangle if isinstance(bars, pd.DataFrame): ohlcTups = [tuple(v) for v in bars[['open', 'high', 'low', 'close']].values] else: ohlcTups = [(b.open, b.high, b.low, b.close) for b in bars] fig, ax = plt.subplots() ax.set_title(title) ax.grid(True) fig.set_size_inches(10, 6) for n, (open_, high, low, close) in enumerate(ohlcTups): if close >= open_: color = upColor bodyHi, bodyLo = close, open_ else: color = downColor bodyHi, bodyLo = open_, close line = Line2D( xdata=(n, n), ydata=(low, bodyLo), color=color, linewidth=1) ax.add_line(line) line = Line2D( xdata=(n, n), ydata=(high, bodyHi), color=color, linewidth=1) ax.add_line(line) rect = Rectangle( xy=(n - 0.3, bodyLo), width=0.6, height=bodyHi - bodyLo, edgecolor=color, facecolor=color, alpha=0.4, antialiased=True ) ax.add_patch(rect) ax.autoscale_view() return fig
def plot_behavior_cluster(centroids, num_clusters): ''' Plots computed clusters. Parameters ---------- Centroids : array Predicted centroids of clusters. num_clusters: int Number of clusters. Returns ------- Plot : matplotlib.lines.Line2D Figure. ''' # Figure has all clusters on same plot. fig = plt.figure(figsize=(10,7)) ax = fig.add_subplot(1,1,1) # Set colors. colors = cm.rainbow(np.linspace(0, 1, num_clusters)) # Plot cluster and corresponding color. for cluster, color in enumerate(colors, start =1): ax.plot(centroids[cluster-1], c = color, label = "Cluster %d" % cluster) # Format figure. ax.set_title("Centroids of consumption pattern of clusters, where k = %d" % num_clusters, fontsize =14, fontweight='bold') ax.set_xlim([0, 24]) ax.set_xticks(range(0, 25, 6)) ax.set_xlabel("Time (h)") ax.set_ylabel("Consumption (kWh)") leg = plt.legend(frameon = True, loc = 'upper left', ncol =2, fontsize = 12) leg.get_frame().set_edgecolor('b') plt.show()
def plot_cluster_hist(X_featurized, labels, num_clusters): ''' Plot histograms of users and corresponding clusters. Parameters ---------- X_featurized : array-like Featurized Data labels: array-like Predicted cluster to data. num_clusters: int Number of clusters. Returns ------- Plot : matplotlib.lines.Line2D Figure. ''' fig = plt.figure() ax_ = fig.add_subplot(1,1,1) # Set colors. # Create DataFrame with features and labels. # Note sklearn cluster naming starts at zero, so adding 1 is convenient. X_featurized['label'] = labels + 1 # Parameters for plotting. params_ = {'ax': ax_ , 'bins': np.arange(num_clusters +2) - 0.5} # Plot cluster and corresponding color. X_featurized.label.plot(kind = 'hist', **params_) # Format figure. ax_.set_title("Number of users in each cluster.", fontsize =14, fontweight='bold') ax_.set_xticks(range(1, num_clusters +1)) ax_.set_xlim([0, num_clusters + 1]) ax_.set_ylim([0,1200]) ax_.set_xlabel('Cluster') ax_.set_ylabel("Number of users") # plt.savefig('cluster_hist') plt.show()