def legend(self, handles, labels, loc, **kwargs): """ Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of line or patch instances, and loc can be a string or an integer specifying the legend location USAGE: legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right') The LOC location codes are 'best' : 0, (currently not supported, defaults to upper right) 'upper right' : 1, (default) 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, The legend instance is returned """ handles = flatten(handles) l = Legend(self, handles, labels, loc, isaxes=False, **kwargs) self._set_artist_props(l) self.legends.append(l) return l
def __init__(self, data=None, **kwtraits): if 'origin' in kwtraits: self.default_origin = kwtraits.pop('origin') if "title" in kwtraits: title = kwtraits.pop("title") else: title = None super(Plot, self).__init__(**kwtraits) if data is not None: if isinstance(data, AbstractPlotData): self.data = data elif type(data) in (ndarray, tuple, list): self.data = ArrayPlotData(data) else: raise ValueError, "Don't know how to create PlotData for data" \ "of type " + str(type(data)) if not self._title: self._title = PlotLabel(font="swiss 16", visible=False, overlay_position="top", component=self) if title is not None: self.title = title if not self.legend: self.legend = Legend(visible=False, align="ur", error_icon="blank", padding=10, component=self) # ensure that we only get displayed once by new_window() self._plot_ui_info = None return
def __init__(self, stop_list): pygame.init() self.stop_list = stop_list self.screen = pygame.display.set_mode(SIZE) pygame.display.set_caption("bus-stop") self.set_screen() self.clock = pygame.time.Clock() self.all_bus = pygame.sprite.Group() self.legend = Legend() self.running = True
def legend(self, handles, labels, *args, **kwargs): """ Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of line or patch instances, and loc can be a string or an integer specifying the legend location USAGE: legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right') The LOC location codes are 'best' : 0, (currently not supported for figure legends) 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, loc can also be an (x,y) tuple in figure coords, which specifies the lower left of the legend box. figure coords are (0,0) is the left, bottom of the figure and 1,1 is the right, top. The legend instance is returned. The following kwargs are supported: loc = "upper right" # numpoints = 4 # the number of points in the legend line prop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ handles = flatten(handles) l = Legend(self, handles, labels, *args, **kwargs) self._set_artist_props(l) self.legends.append(l) return l
def add_legend_to_map(the_map): """Add a default legend to a folium map. Parameters ---------- the_map : object like folium.folium.Map The map we are to add the tiles to. """ labels = [] for key, val in COLORS_PARTY.items(): labels.append({'text': key, 'color': val, 'opacity': OPACITY}) legend = Legend(title='Partier', labels=labels) the_map.add_child(legend)
def processTrackerGGLegendData(o, all_legend_names): legend_data = list() #process reponse data for legend in all_legend_names: #set default kills to 0 kills = 0; for item in o["data"]: #if legend name matches a player data legend name then attempt to get kill data if item.get("metadata").get("name") == legend: #if kill data is available then set value of kills if item.get("stats") and item.get("stats").get("kills") and item.get("stats").get("kills").get("value"): kills = int(item["stats"]["kills"]["value"]) #initialise Legend object for each legend using name and kills as parameters. legend_data.append(Legend(legend, kills)) pass return legend_data
def __init__(self, json_obj): self.title = json_obj["title"] self.label = json_obj["label"] self.legend = [] for legend in json_obj["legend"]: self.legend.append(Legend(legend)) self.rows = json_obj["rows"] self.columns = json_obj["columns"] self.bars = [] for bar in json_obj["bars"]: self.bars.append(Bar(bar)) self.bar_height = json_obj["bar_height"]
def __init__(self, figure, axis=None): """ Create the drawable with the figure. :param figure: The figure that the :class:`~Drawable` class wraps. This is mainly used to get the figure renderer. :type figure: :class:`matplotlib.figure.Figure` :param axis: The axis (or subplot) where to plot visualizations. If `None` is not given, the plot's main subplot is used instead. :type axis: `None` or :class:`matplotlib.axis.Axis` """ self.figure = figure self.axis = plt.gca() if axis is None else axis self.caption = Annotation(self) self.annotations = [] self.legend = Legend(self) self.timeseries = None
def update(self, string): QObjectCleanupHandler().add(self.layout()) scroll_bar_position = self.scroll.horizontalScrollBar().value() for widgets in self.findChildren(QWidget): widgets.deleteLater() dictionary = json.loads(string) credit = dictionary["creditos"] dictionary = dictionary["malla"] hbox = QHBoxLayout() legend = Legend() hbox.addWidget(legend) for semester_number in [ str(index) for index in range(1, len(dictionary) + 1) ]: height = self.geometry().height() * semester_height_scale semester = Semester(number=semester_number, credit=credit[semester_number], height=height) semester.add_subjects(dictionary[semester_number]) hbox.addWidget(semester) semester.send_semester_update.connect(self.receive_semester_update) semester.send_subject_state_update.connect( self.receive_subject_state_update) groupBox = QGroupBox() groupBox.setLayout(hbox) self.scroll = QScrollArea() self.scroll.setWidget(groupBox) self.scroll.setWidgetResizable(True) self.scroll.horizontalScrollBar().setValue(scroll_bar_position) hbox = QHBoxLayout() hbox.addWidget(self.scroll) self.setLayout(hbox)
def __init__(self): self.img = None self.legend = Legend() self.title = Title() self.autosize = App.cfg['image']['autosize'] self.autosize_minpx = App.cfg['image']['autosize_minpx'] self.basewidth = App.cfg['image']['basewidth'] self.baseheight = App.cfg['image']['baseheight'] self.padding = App.cfg['image']['padding'] self.showborder = App.cfg['image']['border'] self.showtitle = App.cfg['title']['show'] self.showlegend = App.cfg['legend']['show'] self.showgrid = App.cfg['axis']['grid'] self.showaxis = App.cfg['axis']['show'] self.showflat = App.cfg['image']['flatline'] self.showtimestamp = App.cfg['image']['timestamp'] self.timestampcolor = App.cfg['image']['timestampcolor'] self.bordercolor = App.cfg['image']['bordercolor'] self.streetcolor = App.cfg['image']['streetcolor'] self.flatcolor = App.cfg['image']['flatcolor'] self.gridcolor = App.cfg['axis']['gridcolor'] self.axiscolor = App.cfg['axis']['color'] self.axisfont = App.cfg['axis']['font'] self.bgcolor = App.cfg['image']['bgcolor']
import json from legend import Legend import logging with open("config/config.json") as f: config = json.load(f) logging.basicConfig(level=logging.CRITICAL) legend = Legend(config)
if __name__ == "__main__": args = args() map_fp_lst = args.input_imgs print("Running mapping") # Open image files layers = [] for map_fp in map_fp_lst: im = Image.open(map_fp) print(map_fp, im.format, im.size, im.mode) layers.append(im) #im.show() # Get a legend for this map legend = Legend() if args.legend: legend = Legend(layers) else: print("Loading legend.json") legend = Legend.load('legend.json') if args.specials_dir: if not os.path.isdir(args.specials_dir): print("Cannot open directory of special composites: {}".format(args.specials_dir)) print("Skipping special composites") else: print("Using specials directory '{}'".format(args.specials_dir)) else: print("Skipping special composites")
def visualize(self): import matplotlib.patches as mpatches self.fig, self.ax = plt.subplots(3, 1, sharex=True) self.ax[0].set_title('Click on legend rectangle to toggle data on/off', fontdict={'fontsize' : 8 }) self.fig.set_size_inches(12, 7, forward=True) plt.subplots_adjust(left=0.05, bottom=0.15, right=0.98, hspace=0.15) # bpdiff_trans = [] # major transition self.ax = self.ax[::-1] # major가 같은 것 들만 print('Run matplotlib...') for i in range(len(self.bpdiff)): sc = [ {'major' : [], 'minor': [] }, {'major' : [], 'minor': [] }, {'major' : [], 'minor': [] }, {'major' : [], 'minor': [] } ] self.draw_vspans(self.ax[i], self.B.range_dumas) for a in range(4): cond1 = self.bpdiff[i]['Mj_seq_x'] == a # major a -> minor b for b in range(4): if a == b: # sc[a]['major'].append(None) # sc[a]['minor'].append(None) continue # 1. minor가 같은 것들 처리 : 같은 색상 cond2 = self.bpdiff[i]['Mn_seq_y'] == b # x는 cond3 = logical_or(self.bpdiff[i]['minor_x'] == 0, self.bpdiff[i]['Mn_seq_x'] == b) cond3 = logical_and(cond2, cond3) d = self.B.get_bpdiff_cond(index=i, cond=logical_and(cond1, cond3)) #bpdiff[i][ logical_and(cond1, cond3).values ] if len(d) > 0: y_ = [ linspace(d_.maf_x, d_.maf_y, self.seq_size) for d_ in d[['maf_x', 'maf_y']].itertuples() ] x_ = array(y_) for j in range(len(d)): x_[j].fill( d[self.duma_position].values[j] ) c = [ self.xlin for _ in range(len(x_))] sc[a]['minor'].append(self.ax[i].scatter(x_, y_, c=c, cmap=mcols.cmap(self.mcolor[b]), s=self.markersize, linewidth=0.0)) # draw major scatter y_ = self.get_uppery(y_) x_ = [ ii[0] for ii in x_] sc[a]['major'].append(self.ax[i].scatter(x_, y_, color=self.basecolors[a], label=self.basepair[a], s=self.markersize-1)) # # 2. minor가 바뀌는 것들 처리 : colors diverging # 각 basetype -> b type, target이 b, 즉, b로 변한것 cond2 = logical_and(self.bpdiff[i]['Mn_seq_x'] != b, self.bpdiff[i]['minor_x'] > 0) cond3 = logical_and(cond2, self.bpdiff[i]['Mn_seq_y'] == b) d = self.bpdiff[i][ logical_and(cond1, cond3).values ] if len(d) > 0: self.draw_minor_transition(self.ax[i], sc, d, a, b) # end for b #end for a self.sct.append(sc) self.ax[i].set_ylim([0, 50]) self.ax[i].set_ylabel('Variation of MAF(%)') self.ax[i].set_title(self.ylabel[i], loc='left', fontdict={'fontsize':13, 'verticalalignment':'top', 'color':'black', 'backgroundcolor':'#FEFEFE'}) # ZoomSlider of Dumas position zaxes = plt.axes([0.08, 0.07, 0.90, 0.03], facecolor='lightgoldenrodyellow') self.zslider = ZoomSlider(zaxes, 'Dumas Position', valmin=self.B.minpos, valmax=self.B.maxpos, valleft=self.B.minpos, valright=self.B.maxpos, color='lightblue', valstep=1.0) self.zslider.on_changed(self.update_xlim) from legend import Legend spatches = [ mpatches.Patch(color=self.basecolors[idx], label=self.basepair[idx]) for idx in range(4) ] leg_basepair = Legend(self.fig, { 'spatches' : spatches, 'label' : self.basepair, 'bbox':(0.66, .91, 0.33, .102), 'loc' : 3, 'ncol' : 4, 'mode' : 'expand', 'borderaxespad' : 0.}) dumalabels = [ key for key in self.dumas.keys()] spatches = [ mpatches.Patch(color='grey', label=dumalabels[idx]) for idx in range(3) ] leg_dumas = Legend(self.fig, { 'spatches' : spatches, 'label' : dumalabels, 'bbox':(0.05, .91, 0.33, .102), 'loc' : 3, 'ncol' : 3, 'mode' : 'expand', 'borderaxespad' : 0.}) spatches = [ mpatches.Patch(color=['black', 'magenta'][idx], label=['base', 'variation'][idx]) for idx in range(2) ] self.leg_filter = Legend(self.fig, { 'spatches' : spatches, 'label' : ['base_0.0', 'variation_5.0'], 'bbox':(0.40, .91, 0.24, .102), 'loc' : 3, 'ncol' : 3, 'mode' : 'expand', 'borderaxespad' : 0.}) for x in self.ax: self.annot.append(x.annotate("", xy=(0,0), xytext=(20,-30),textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->"))) # annotate over other axes x.figure.texts.append(x.texts.pop()) # # x.callbacks.connect('xlim_changed', xlim_changed_event) for c in self.B.range_dumas.keys(): self.annot_gere[c] = [] ay_ = 0.85 if c == self.duma_Repeat else 0.7 if c == self.duma_ORF: ay_ = 1. for d in self.dumas[c]: self.annot_gere[c].append(self.ax[-1].annotate(d, xy=(self.B.range_dumas[c][d]['min'], 50*ay_), xytext=(-20,10), textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="fancy"))) for an_ in self.annot: an_.set_visible(False) an_.set_zorder(10) for c in self.B.range_dumas.keys(): for an_ in self.annot_gere[c]: an_.set_visible(False) # legend pick event self.fig.canvas.mpl_connect('pick_event', self.onpick) leg_dumas.pick() self.fig.canvas.mpl_connect("button_press_event", self.click_) # ax[-1].text(105500, 49, 'IRS', fontdict={'fontsize':5}) # buttonaxes = plt.axes([0.89, .95, 0.1, 0.025]) # bnext = Button(buttonaxes, 'Export') # bnext.on_clicked(ExportToParallelCoordGraph) plt.show()
def __init__(self, *args, **kwargs): """ Sets up the UI, binds the events etc """ super(French75, self).__init__(*args, **kwargs) #WorldState.Instance() = WorldState.Instance() self.Maximize() (WorldState.Instance().dispW, WorldState.Instance().dispH) = self.GetSize() splitter_far_right = wx.SplitterWindow(self, -1) splitter_horiz_middle = wx.SplitterWindow(splitter_far_right, -1) splitter_vert_middle = wx.SplitterWindow(splitter_horiz_middle) splitter_far_right_middle = wx.SplitterWindow(splitter_far_right, -1) self.legend_panel = scrolled.ScrolledPanel(splitter_vert_middle, -1) self.graph_panel = wx.Panel(splitter_vert_middle, -1) self.legend_panel.SetBackgroundColour(_BG_COLOUR) self.graph_panel.SetBackgroundColour(_BG_COLOUR) """ Animation Panel Setup """ self.animation_panel = scrolled.ScrolledPanel(splitter_horiz_middle, -1) self.animation_panel.SetBackgroundColour(_BG_COLOUR) self.btn_animate_play = wx.Button(self.animation_panel, -1, 'Play') self.btn_animate_play.Bind(wx.EVT_BUTTON, self.play_animation) self.slider_time = wx.Slider( self.animation_panel, -1, value=0, minValue=0, maxValue=WorldState.Instance().session_dict['max_time'], style=wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS) self.slider_time.Bind(wx.EVT_SLIDER, self.move_animation) self.slider_time.Bind(wx.EVT_SCROLL_THUMBRELEASE, self.released_slider) self.drop_down_species = wx.ComboBox(self.animation_panel, -1, style=wx.CB_READONLY) self.drop_down_species.Bind(wx.wx.EVT_COMBOBOX, self.change_animation_species) self.switch_animation_button = wx.Button(self.animation_panel, -1, "<->") self.switch_animation_button.Bind(wx.EVT_BUTTON, self.switch_animation) self.drop_down_files = wx.ComboBox(self.animation_panel, -1, style=wx.CB_READONLY) self.drop_down_files.Bind(wx.wx.EVT_COMBOBOX, self.change_animation_file) line1 = wx.StaticLine(self.animation_panel, -1, style=wx.LI_VERTICAL) line3 = wx.StaticLine(self.animation_panel, -1, style=wx.LI_VERTICAL) line2 = wx.StaticLine(self.animation_panel) animation_vbox = wx.BoxSizer(wx.VERTICAL) animation_hbox = wx.BoxSizer(wx.HORIZONTAL) self.animation_panels_hbox = wx.BoxSizer(wx.HORIZONTAL) animation_hbox.Add(self.drop_down_files, 0, wx.ALL, 10) animation_hbox.Add(self.switch_animation_button, 0, wx.TOP, 12) animation_hbox.Add(self.drop_down_species, 0, wx.ALL, 10) animation_hbox.Add(line1, 0, wx.EXPAND | wx.ALL, 5) animation_hbox.Add(self.btn_animate_play, 0, wx.TOP, 12) animation_hbox.Add(line3, 0, wx.EXPAND | wx.ALL, 5) animation_hbox.Add(self.slider_time, 0, wx.BOTTOM | wx.EXPAND | wx.ALIGN_RIGHT, 5) animation_vbox.Add(animation_hbox, 0) animation_vbox.Add(line2, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 10) animation_vbox.Add(self.animation_panels_hbox) self.animation_panel.SetSizer(animation_vbox) self.animation_panel.Layout() self.animation_panel.SetupScrolling(scroll_y=False) """ Attached Files Panel Setup """ attachment_panel = wx.Panel(splitter_far_right_middle, -1) attachment_panel.SetBackgroundColour(_BG_COLOUR) attached_files_vbox = wx.BoxSizer(wx.VERTICAL) attached_file_toolbar = wx.BoxSizer(wx.HORIZONTAL) attached_label = wx.StaticText(attachment_panel, -1, "Attached Files:") attached_files_vbox.Add(attached_label, 0, wx.EXPAND | wx.TOP | wx.LEFT, 5) self.attached_file_list = wx.ListBox(attachment_panel, -1, size=(300, 300)) attached_files_vbox.Add(self.attached_file_list) self.add_files_button = wx.Button(attachment_panel, -1, "Add") self.add_files_button.Bind(wx.EVT_BUTTON, self.attach_file) self.open_files_button = wx.Button(attachment_panel, -1, "Open") self.open_files_button.Bind(wx.EVT_BUTTON, self.open_attached_file) attached_file_toolbar.Add(self.add_files_button, 0, wx.ALL, 5) attached_file_toolbar.Add(self.open_files_button, 0, wx.ALL, 5) attached_files_vbox.Add(attached_file_toolbar, 0, wx.ALL | wx.ALIGN_CENTRE, 5) attachment_panel.SetSizer(attached_files_vbox) attached_files_vbox.Fit(self) """ Animation Annotations Panel Setup """ annotation_panel = wx.Panel(splitter_far_right_middle, -1) annotation_panel.SetBackgroundColour(_BG_COLOUR) anime_annotations_vbox = wx.BoxSizer(wx.VERTICAL) anime_annotations_toolbar = wx.BoxSizer(wx.HORIZONTAL) anime_annotations_label = wx.StaticText(annotation_panel, -1, "Animation Annotations:") anime_annotations_vbox.Add(anime_annotations_label, 0, wx.EXPAND | wx.TOP | wx.LEFT, 5) self.anime_annotations_list = wx.ListBox(annotation_panel, -1, size=(300, 300)) anime_annotations_vbox.Add(self.anime_annotations_list) self.add_anime_annotation_button = wx.Button(annotation_panel, -1, "Add") self.add_anime_annotation_button.Bind(wx.EVT_BUTTON, self.add_anime_annotation) self.delete_anime_annotation_button = wx.Button( annotation_panel, -1, "Remove") self.delete_anime_annotation_button.Bind(wx.EVT_BUTTON, self.remove_anime_annotation) anime_annotations_toolbar.Add(self.add_anime_annotation_button, 0, wx.ALL, 5) anime_annotations_toolbar.Add(self.delete_anime_annotation_button, 0, wx.ALL, 5) anime_annotations_vbox.Add(anime_annotations_toolbar, 0, wx.ALL | wx.ALIGN_CENTRE, 5) annotation_panel.SetSizer(anime_annotations_vbox) anime_annotations_vbox.Fit(self) """ Graph Panel Setup """ (graph_width, graph_height) = calc_graph_size(_DPI, _COLS, _NUM_OF_SIDEBARS, _PHI) graph_fig = Figure((graph_width, graph_height)) graph_fig.set_facecolor('white') self.graph_canvas = FigCanvas(self.graph_panel, -1, graph_fig) self.graph_axes = graph_fig.add_subplot(111) graph_vbox = wx.BoxSizer(wx.VERTICAL) graph_vbox.Add(self.graph_canvas) self.toolbar = BioPepaToolbar(self.graph_canvas) (toolW, toolH) = self.toolbar.GetSizeTuple() graph_vbox.Add(self.toolbar) self.graph_panel.SetSizer(graph_vbox) graph_vbox.Fit(self) self.graph_canvas.mpl_connect('button_press_event', self.onclick) self.graph_canvas.mpl_connect('motion_notify_event', self.move_mouse) """ Legend Panel Setup """ title = wx.StaticText(self.legend_panel, wx.ID_ANY, 'Legend', style=wx.ALIGN_LEFT) font = wx.Font(28, wx.DEFAULT, wx.NORMAL, wx.BOLD) title.SetFont(font) vbox_leg = wx.BoxSizer(wx.VERTICAL) vbox_leg.Add(title, flag=wx.CENTER) self.legend_panel.SetSizer(vbox_leg) self.legend_panel.Layout() """ Menubar Setup """ self.SetMenuBar(self.build_menu_bar()) """ WorldState Stuff """ WorldState.Instance().drop_down_species = self.drop_down_species WorldState.Instance().drop_down_files = self.drop_down_files WorldState.Instance( ).create_cell_segments_by_species = self.create_cell_segments_by_species WorldState.Instance( ).create_cell_segments_by_file = self.create_cell_segments_by_file WorldState.Instance().graph_canvas = self.graph_canvas WorldState.Instance().play_animation = self.real_play_animation WorldState.Instance( ).create_cell_segments_by_file = self.create_cell_segments_by_file WorldState.Instance( ).create_cell_segments_by_species = self.create_cell_segments_by_species WorldState.Instance().time_slider = self.slider_time WorldState.Instance( ).anime_annotations_list = self.anime_annotations_list WorldState.Instance().graph_axes = self.graph_axes WorldState.Instance().graph_width = graph_width WorldState.Instance().graph_height = graph_height WorldState.Instance().legend = Legend(self.legend_panel) WorldState.Instance().update_title = self.SetTitle WorldState.Instance().get_title = self.GetTitle """ Whole UI Setup """ splitter_far_right.SplitVertically(splitter_horiz_middle, splitter_far_right_middle) splitter_horiz_middle.SplitHorizontally(splitter_vert_middle, self.animation_panel) splitter_vert_middle.SplitVertically(self.graph_panel, self.legend_panel) splitter_far_right_middle.SplitHorizontally(attachment_panel, annotation_panel) splitter_far_right.SetSashPosition((5 * WorldState.Instance().dispW / 6) + 10) splitter_vert_middle.SetSashPosition((4 * WorldState.Instance().dispW / 6) - 10) splitter_horiz_middle.SetSashPosition((graph_height * _DPI) + toolH + 5) splitter_far_right_middle.SetSashPosition(WorldState.Instance().dispH / 2) self.SetTitle(_TITLE) self.enable_all(False) self.filem_new_session.Enable(True) self.filem_load_session.Enable(True) self.Maximize()
def legend(self, handles, labels, *args, **kwargs): """ Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of :class:`~matplotlib.lines.Line2D` or :class:`~matplotlib.patches.Patch` instances, and loc can be a string or an integer specifying the legend location USAGE:: legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right') The *loc* location codes are:: 'best' : 0, (currently not supported for figure legends) 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, *loc* can also be an (x,y) tuple in figure coords, which specifies the lower left of the legend box. figure coords are (0,0) is the left, bottom of the figure and 1,1 is the right, top. Keyword arguments: *prop*: [ None | FontProperties | dict ] A :class:`matplotlib.font_manager.FontProperties` instance. If *prop* is a dictionary, a new instance will be created with *prop*. If *None*, use rc settings. *numpoints*: integer The number of points in the legend line, default is 4 *scatterpoints*: integer The number of points in the legend line, default is 4 *scatteroffsets*: list of floats a list of yoffsets for scatter symbols in legend *markerscale*: [ None | scalar ] The relative size of legend markers vs. original. If *None*, use rc settings. *fancybox*: [ None | False | True ] if True, draw a frame with a round fancybox. If None, use rc *shadow*: [ None | False | True ] If *True*, draw a shadow behind legend. If *None*, use rc settings. *ncol* : integer number of columns. default is 1 *mode* : [ "expand" | None ] if mode is "expand", the legend will be horizontally expanded to fill the axes area (or *bbox_to_anchor*) *title* : string the legend title Padding and spacing between various elements use following keywords parameters. The dimensions of these values are given as a fraction of the fontsize. Values from rcParams will be used if None. ================ ================================================================== Keyword Description ================ ================================================================== borderpad the fractional whitespace inside the legend border labelspacing the vertical space between the legend entries handlelength the length of the legend handles handletextpad the pad between the legend handle and text borderaxespad the pad between the axes and legend border columnspacing the spacing between columns ================ ================================================================== .. Note:: Not all kinds of artist are supported by the legend. See LINK (FIXME) for details. **Example:** .. plot:: mpl_examples/pylab_examples/figlegend_demo.py """ handles = flatten(handles) l = Legend(self, handles, labels, *args, **kwargs) self.legends.append(l) return l
def legend(self, handles, labels, *args, **kwargs): """ Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of :class:`~matplotlib.lines.Line2D` or :class:`~matplotlib.patches.Patch` instances, and loc can be a string or an integer specifying the legend location USAGE:: legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right') The *loc* location codes are:: 'best' : 0, (currently not supported for figure legends) 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, *loc* can also be an (x,y) tuple in figure coords, which specifies the lower left of the legend box. figure coords are (0,0) is the left, bottom of the figure and 1,1 is the right, top. The legend instance is returned. The following kwargs are supported *loc* the location of the legend *numpoints* the number of points in the legend line *prop* a :class:`matplotlib.font_manager.FontProperties` instance *pad* the fractional whitespace inside the legend border *markerscale* the relative size of legend markers vs. original *shadow* if True, draw a shadow behind legend *labelsep* the vertical space between the legend entries *handlelen* the length of the legend lines *handletextsep* the space between the legend line and legend text *axespad* the border between the axes and legend edge .. plot:: mpl_examples/pylab_examples/figlegend_demo.py """ handles = flatten(handles) l = Legend(self, handles, labels, *args, **kwargs) self.legends.append(l) return l
def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.setModal(True) self.setWindowTitle("Running jobs") self.setMinimumWidth(250) #self.setMinimumHeight(250) self.ctrl = SimulationsDialogController(self) self.simulationProgress = QtGui.QProgressBar() self.simulationProgress.setValue(0) self.connect(self.simulationProgress, QtCore.SIGNAL('setValue(int)'), self.updateProgress) self.cogwheel = Cogwheel(size=20) memberLayout = QtGui.QVBoxLayout() progressLayout = QtGui.QHBoxLayout() progressLayout.addWidget(self.simulationProgress) progressLayout.addWidget(self.cogwheel) memberLayout.addLayout(progressLayout) simulationLayout = QtGui.QHBoxLayout() self.simulationList = SimulationList() self.simulationList.contextMenuEvent = self._contextMenu self.connect(self.simulationList, QtCore.SIGNAL('itemSelectionChanged()'), self.ctrl.selectSimulation) simulationLayout.addWidget(self.simulationList) self.simulationPanel = SimulationPanel() simulationLayout.addWidget(self.simulationPanel) memberLayout.addLayout(simulationLayout) legendLayout = QtGui.QHBoxLayout() legendLayout.addLayout( Legend("Not active", SimulationItemDelegate.notactive)) legendLayout.addLayout( Legend("Waiting", SimulationItemDelegate.waiting)) legendLayout.addLayout( Legend("Pending", SimulationItemDelegate.pending)) legendLayout.addLayout( Legend("Running", SimulationItemDelegate.running)) legendLayout.addLayout( Legend("User killed", SimulationItemDelegate.userkilled)) legendLayout.addLayout(Legend("Failed", SimulationItemDelegate.failed)) legendLayout.addLayout( Legend("Finished", SimulationItemDelegate.finished)) memberLayout.addLayout(legendLayout) self.doneButton = QtGui.QPushButton("Done", self) self.connect(self.doneButton, QtCore.SIGNAL('clicked()'), self.accept) buttonLayout = QtGui.QHBoxLayout() self.estimateLabel = QtGui.QLabel() buttonLayout.addWidget(self.estimateLabel) buttonLayout.addStretch(1) buttonLayout.addWidget(self.doneButton) memberLayout.addSpacing(10) memberLayout.addLayout(buttonLayout) self.setLayout(memberLayout)
#end for a sct.append(sc) ax[i].set_ylim([0, 50]) ax[i].set_ylabel('Variation of MAF(%)') ax[i].set_title(ylabel[i], loc='left', fontdict={'fontsize':13, 'verticalalignment':'top', 'color':'black', 'backgroundcolor':'#FEFEFE'}) # ZoomSlider of Dumas position zaxes = plt.axes([0.08, 0.07, 0.90, 0.03], facecolor='lightgoldenrodyellow') zslider = ZoomSlider(zaxes, 'Dumas Position', valmin=B.minpos, valmax=B.maxpos, valleft=B.minpos, valright=B.maxpos, color='lightblue', valstep=1.0) zslider.on_changed(update_xlim) from legend import Legend spatches = [ mpatches.Patch(color=colors[idx], label=basepair[idx]) for idx in range(4) ] leg_basepair = Legend(fig, { 'spatches' : spatches, 'label' : basepair, 'bbox':(0.66, .91, 0.33, .102), 'loc' : 3, 'ncol' : 4, 'mode' : 'expand', 'borderaxespad' : 0.}) dumalabels = [ key for key in dumas.keys()] spatches = [ mpatches.Patch(color='grey', label=dumalabels[idx]) for idx in range(3) ] leg_dumas = Legend(fig, { 'spatches' : spatches, 'label' : dumalabels, 'bbox':(0.05, .91, 0.33, .102), 'loc' : 3, 'ncol' : 3, 'mode' : 'expand', 'borderaxespad' : 0.}) spatches = [ mpatches.Patch(color=['black', 'magenta'][idx], label=['base', 'variation'][idx]) for idx in range(2) ] leg_filter = Legend(fig, { 'spatches' : spatches, 'label' : ['base_0.0', 'variation_5.0'], 'bbox':(0.40, .91, 0.24, .102), 'loc' : 3, 'ncol' : 3, 'mode' : 'expand', 'borderaxespad' : 0.}) for x in ax: annot.append(x.annotate("", xy=(0,0), xytext=(20,-30),textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->"))) # annotate over other axes x.figure.texts.append(x.texts.pop())
def buildmap(lot, wfr, testset): #--------------------------------------------------------------------------- # Get actual extents... that is number of rows & cols in the wafermap, # If the demodata routine was used, a random number of rows/cols were # generated. #--------------------------------------------------------------------------- min_Y = min(d.Y for d in wfr.dielist) max_Y = max(d.Y for d in wfr.dielist) min_X = min(d.X for d in wfr.dielist) max_X = max(d.X for d in wfr.dielist) col_count = max_X - min_X+1 row_count = max_Y - min_Y+1 log.debug('Die Extents: X = {} to {} Y = {} to {}'.format(min_X, max_X, min_Y, max_Y)) log.debug('Columns (X) = {}, Rows (Y) = {} (Total Die={})'.format(col_count, row_count, len(wfr.dielist))) baseWidth=App.cfg['image']['basewidth'] baseHeight=App.cfg['image']['baseheight'] if baseWidth >= baseHeight: sizeRatio = float(baseWidth) / float(baseHeight) else: sizeRatio = float(baseHeight) / float(baseWidth) log.debug('Size Ratio: {:.2f}, width={}, height={}'.format(sizeRatio, baseWidth, baseHeight)) #--------------------------------------------------------------------------- # If image autosize is enabled, the canvas size may be increased to ensure # die are visible. This will force a minimum pixel size of "autosize_minpx". # The original aspect ratio will be maintained. #--------------------------------------------------------------------------- padding=App.cfg['image']['padding'] autosize_minpx = App.cfg['image']['autosize_minpx'] if App.cfg['image']['autosize']: # conveniences for calculations... bw = App.cfg['image']['basewidth'] bh = App.cfg['image']['baseheight'] autominX = (autosize_minpx * col_count) + (2 * padding) autominY = (autosize_minpx * row_count) + (2 * padding) log.debug('Autosize Minimum Map Size X={} Y={} at Autopx = {}'.format( autominX, autominY, autosize_minpx)) if(autominX > bw): bw = autominX bh = int (float(bw) * float(sizeRatio)) log.debug('Autosize (autominX > bw) Updated sizes - width={}, height={}, sizeRatio={}'.format(bw, bh, float(sizeRatio))) elif (autominY > bh): bh = autominY bw = int (float(bh) * float(sizeRatio)) log.debug('Autosize (autominY > bh) Updated sizes - width={}, height={}, sizeRatio={}'.format(bw, bh, float(sizeRatio))) else: log.debug('Autosize sizing not required, width={}, height={}, autominX={}, autominY={}'.format(bw, bh, autominX, autominY)) #Store updated values back in cfg App.cfg['image']['basewidth'] = bw App.cfg['image']['baseheight'] = bh # Nominal size of map excluding padding mapX = App.cfg['image']['basewidth'] - (padding *2) mapY = App.cfg['image']['baseheight'] - (padding *2) log.debug('Map Space (BaseSize - 2*Padding) (X,Y)=({},{})'.format(mapX,mapY)) #Calculate the die's pixel size width (X) and height (Y) X_pixels = mapX / col_count #X-diesize in pixels Y_pixels = mapY / row_count #Y diesize in pixels log.debug('Pixels per die: X={}, Y={}'.format(X_pixels, Y_pixels)) #--------------------------------------------------------------------------- # Unless the nominal image size (Canvas size minus padding) happens to be an # exact multiple of the calculated die size in pixels, we will have some # space left on all sides. # Calculate the extra space so we can center the image on the canvas #--------------------------------------------------------------------------- slackX = (mapX - (X_pixels * col_count)) / 2 slackY = (mapY - (Y_pixels * row_count)) / 2 log.debug('Slack: X={}, Y={}'.format(slackX, slackY)) log.debug('Calculated Map Size (excluding slack) - (X,Y) = ({},{})'.format( X_pixels * col_count, Y_pixels * row_count)) # #------------------------------------------------------------------------- # Generate the legend data, it will be rendered later, but we require # knowing the space it will take up so we can adjust the canvas size #------------------------------------------------------------------------- wfr.legend = Legend(wfr.dielist, testset) #-------------------------------------------------------------------------- # baseWidth adjusted to allow for legend. #-------------------------------------------------------------------------- actualWidth = App.cfg['image']['basewidth'] if App.cfg['legend']['show']: actualWidth += wfr.legend.legend['legendwidth'] log.debug('Legend Width = {}'.format(wfr.legend.legend['legendwidth'])) #-------------------------------------------------------------------------- # Get axis space, add in 10 pixels for flat spacing. (the axes are # shifted left or up by 10 pixels when they are drawn to account for these # 10 pixels). #-------------------------------------------------------------------------- axis_space = 0 if App.cfg['axis']['show']: axis_space = _do_axis(wfr.dielist,X_pixels,Y_pixels) + 10 log.debug('Axis Space = {}'.format(axis_space)) #-------------------------------------------------------------------------- # baseheight and fontsize adjusted for title #-------------------------------------------------------------------------- # Start with a reasonable guess for the size of the title font and then # autosize it from there. May not be the most efficient way to do # this, but it works for now... #-------------------------------------------------------------------------- actualHeight = App.cfg['image']['baseheight'] titleheight = 0 if App.cfg['title']['show']: #A guess... title_fontsize = actualWidth//40 titlekeys = wfr.legend.titlesize(lot.mir, wfr, title_fontsize, testset) upsearch=False if(titlekeys['maxfw'] > actualWidth): while titlekeys['maxfw'] > actualWidth: upsearch=False title_fontsize -= 1 titlekeys = wfr.legend.titlesize(lot.mir, wfr, title_fontsize, testset) # print "D:imageWith = {}, fontsize = {}, maxfw={}, height={}".format(actualWidth, title_fontsize, titlekeys['maxfw'], titlekeys['maxfh']) else: while titlekeys['maxfw'] < actualWidth: upsearch=True title_fontsize += 1 titlekeys = wfr.legend.titlesize(lot.mir, wfr, title_fontsize, testset) # print "U:imageWith = {}, fontsize = {}, maxfw={}, height={}".format(actualWidth, title_fontsize, titlekeys['maxfw'], titlekeys['maxfh']) # If we were decreasing font size when the while condition became false, all the titlekeys are properly set, # from the last loop cycle.... but if we were increasing font size, the last loop cycle left the titlekeys # in a state for a larger font, so decrease the font size by one and re-evaluate the titlekeys if(upsearch): title_fontsize -=1 titlekeys = wfr.legend.titlesize(lot.mir, wfr, title_fontsize, testset) titleheight = titlekeys['maxfh'] actualHeight += titleheight log.debug('Title Height = {}, Title Fontsize = {}'.format(titleheight, title_fontsize)) #-------------------------------------------------------------------------- # Adjust Width and Height for axis space #-------------------------------------------------------------------------- if(App.cfg['axis']['show']): actualWidth += axis_space actualHeight += axis_space log.debug('Actual Image Size (X,Y) = ({},{})'.format(actualWidth, actualHeight)) log.debug('Padding = {}'.format(padding)) #-------------------------------------------------------------------------- # Create the canvas and draw the wafermap #-------------------------------------------------------------------------- img = Image.new('RGB', (actualWidth,actualHeight), App.cfg['image']['bgcolor']) # Get the drawable object... dr = ImageDraw.Draw(img) # map_extents are used for tracking the actual pixel extents of the drawn map which makes # calculating the location to draw the flat & axis labels a bit easier... map_extents = {'minx':65535, 'miny':65535, 'maxx':0, 'maxy':0} # limit flag_size factor to a minimum of 1.0 (or else flag will exceed die boundary) App.cfg['flag']['size_factor'] = max(App.cfg['flag']['size_factor'], 1.0) # if we want the grid, draw it first so it's behind everything else... if App.cfg['axis']['grid']: _do_grid(wfr.dielist, img, X_pixels, Y_pixels, padding, axis_space, slackX, slackY, titleheight) idx=0 imap = [] for eachDie in wfr.dielist: mybin=getattr(eachDie,App.cfg['binmap']) idx+=1 x1 = padding + axis_space + ((eachDie.X - min_X) * X_pixels) + slackX y1 = padding + axis_space + ((eachDie.Y - min_Y) * Y_pixels) + slackY + titleheight x2 = x1 + X_pixels y2 = y1 + Y_pixels # Draw the die and file with bincolor if eachDie.testset == testset: dr.rectangle([x1,y1,x2,y2], fill=App.cfg['bin'][str(mybin)]['color'], outline=(0,0,0)) imap.append({'Row':eachDie.Y,'Col':eachDie.X,'x':x1,'y':y1,'width':x2-x1,'height':y2-y1}) # Draw any specified symbols, if enabled if App.cfg['enable_symbols']: do_symbol(dr,x1,y1,x2,y2, False, **App.cfg['bin'][str(mybin)]) # Draw flags if appropriate xystr="{}|{}".format(eachDie.X, eachDie.Y) # Bindict Key if (wfr.diedict[xystr]['flags'] & constants.FLAG_MULTITEST) and App.cfg['flag']['show']: if wfr.diedict[xystr]['flags'] & constants.FLAG_DUPLICATE_BIN: flagcolor= App.cfg['flag']['duplicate_color'] else: flagcolor= App.cfg['flag']['split_color'] flagX = int(float(x2-x1)/float(App.cfg['flag']['size_factor'])) flagY = int(float(y2-y1)/float(App.cfg['flag']['size_factor'])) dr.polygon([(x1,y1+flagY),(x1,y1),(x1+flagX,y1)], fill=flagcolor, outline=(0,0,0)) # track minimum and maximums of actual drawn wafermap. map_extents['minx']= min(map_extents['minx'],x1) map_extents['maxx']= max(map_extents['maxx'],x2) map_extents['miny']= min(map_extents['miny'],y1) map_extents['maxy']= max(map_extents['maxy'],y2) log.debug('Drawn Map Extents = {}'.format(map_extents)) # do_html(imap, actualWidth, actualHeight) #-------------------------------------------------------------------------- # Draw title area #-------------------------------------------------------------------------- if App.cfg['title']['show']: dr.rectangle([0,0,actualWidth,titleheight], fill=App.cfg['title']['bgcolor'], outline=(0,0,0)) wfr.legend.render_title(img, wfr, titlekeys) #-------------------------------------------------------------------------- # Draw legend, border, flat indicator, timestamp, axis labels #-------------------------------------------------------------------------- if App.cfg['legend']['show']: wfr.legend.render(App.cfg['image']['basewidth'] + axis_space , padding + titleheight, img) if App.cfg['image']['border']: dr.rectangle([0,0,actualWidth-1,actualHeight-1], fill=None, outline=(0,0,0)) if App.cfg['image']['flatline']: wfr.legend.render_flat(img, lot.wcr['WF_FLAT'], map_extents, (127,0,0)) # wfr.legend.render_flat(img, 'L', map_extents, (127,0,0)) if App.cfg['image']['timestamp']: wfr.legend.timestamp(img, color=(0,0,127)) if App.cfg['axis']['show']: _do_axis(wfr.dielist, X_pixels, Y_pixels, map_extents, img, True) # # Add some debug entries to the configuration for examination during a dump # # (-z command option) # App.cfg['debug']={} # # App.cfg['debug']['Map'] = {'mapX':mapX, 'mapY':mapY, 'X_pixels':X_pixels, 'Y_pixels':Y_pixels, # 'Actual Width':actualWidth, 'Actual Height':actualHeight, # 'Title Height':titleheight, 'Axis Space':axis_space, # 'Slack X':slackX, 'Slack Y':slackY, # 'Drawn Map Extents':map_extents} # # # print "Map X,Y............... {},{}".format(mapX,mapY) # # print "Die Pixels X,Y........ {},{}".format(X_pixels,Y_pixels) # # print "Actual Image Size..... {},{}".format(actualWidth,actualHeight) # # print "Title Height.......... {}".format(titleheight) # # print "Axis Space............ {}".format(axis_space) # # print "Padding............... {}".format(padding) # # print "Drawn Map Extents..... {}".format(map_extents) return(img)
def legend(*args, **kwargs): return Legend(*args, **kwargs)