我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用matplotlib.org()。
def init_canvas(self): """Initializes the matplotlib canvas. Adapted from https://matplotlib.org/examples/user_interfaces/embedding_in_tk.html Generates a frame and palces a figure canvas and a navigation toolbar inside it. """ frame_figure = tk.Frame(self.root, bd=1, relief=tk.SUNKEN) frame_figure.grid(row=0, column=0, sticky=tk.NW+tk.SW) canvas = FigureCanvasTkAgg(self.figure, master=frame_figure) canvas.show() canvas.get_tk_widget().pack() toolbar = NavigationToolbar2TkAgg(canvas, frame_figure) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
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 make_experiment4_figure(logfile): """Generate high quality plot of data to reproduce figure 8. The logfile is a CSV of the format [congestion_control, loss_rate, goodput, rtt, capacity, specified_bw] """ results = {} cubic = {"loss": [], "goodput": []} bbr = {"loss": [], "goodput": []} # For available options on plot() method, see: https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot # We prefer to use explicit keyword syntax to help code readability. # Create a figure. fig_width = 8 fig_height = 5 fig, axes = plt.subplots(figsize=(fig_width, fig_height)) results = parse_results_csv(logfile) xmark_ticks = get_loss_percent_xmark_ticks(results) cubic = results['cubic'] bbr = results['bbr'] debug_print_verbose("CUBIC: %s" % cubic) debug_print_verbose("BBR: %s" % bbr) matplotlib.rcParams.update({'figure.autolayout': True}) plt.plot(cubic['loss'], cubic['goodput'], color='blue', linestyle='solid', marker='o', markersize=7, label='CUBIC') plt.plot(bbr['loss'], bbr['goodput'], color='red', linestyle='solid', marker='x', markersize=7, label='BBR') plt.xscale('log') apply_axes_formatting(axes, deduplicate_xmark_ticks(xmark_ticks)) plot_titles(plt, xaxis="Loss Rate (%) - Log Scale", yaxis="Goodput (Mbps)") plot_legend(plt, axes) save_figure(plt, name="figures/experiment4.png")
def about(self): QtWidgets.QMessageBox.about(self, "About", """QIView Copyright 2017 Tobias Wood A simple viewer for dual-coded overlays. With thanks to http://matplotlib.org/examples/user_interfaces/embedding_in_qt5.html""")
def on_key_press(self, event): print('you pressed', event.key) #implement the default mpl key press events described at # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts key_press_handler(event, self.canvas, self.mpl_toolbar)
def on_key_press(self, event): print('you pressed', event.key) # implement the default mpl key press events described at # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts # key_press_handler(event, self.canvas, self.mpl_toolbar)
def do_plot(self, osc): o = self.create_osc(osc, all_oscillators=self.oscillators) frames = list(itertools.islice(o, self.synth.samplerate)) if not plot: self.statusbar["text"] = "Cannot plot! To plot things, you need to have matplotlib installed!" return plot.figure(figsize=(16, 4)) plot.title("Waveform") plot.plot(frames) plot.show() # @todo properly integrate matplotlib in the tkinter gui because the above causes gui freeze problems # see http://matplotlib.org/examples/user_interfaces/embedding_in_tk2.html
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'): # https://matplotlib.org/examples/color/colormaps_reference.html patches = [] for pos in var: if shape == 'c': patches.append(mpatches.Circle(pos, r)) elif shape == 'r': patches.append(mpatches.RegularPolygon(pos, 4, r)) elif shape == 's': patches.append(mpatches.RegularPolygon(pos, 6, r)) colors = np.linspace(start_color, .9, len(patches)) collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.) collection.set_array(np.array(colors)) collection.set_clim(0, 1) return collection
def purity_efficiency_plot(y_true, y_pred, inset=True, savepath=None): # Purity = precision # Efficiency = recall purity, efficiency, thresholds = precision_recall_curve(y_true[:, 1], y_pred[:, 1]) # Discard last point in purity, efficiency # (sklearn sets them to 1, 0 respectively) purity = purity[:-1] efficiency = efficiency[:-1] # Set larger font for legibility matplotlib.rcParams.update({'font.size': FONT_SIZE}) # Code adapted from http://matplotlib.org/1.3.1/mpl_toolkits/axes_grid/examples/inset_locator_demo.py fig, ax = plt.subplots() # Plot purity and efficiency ax.plot(thresholds, purity, label="Purity") ax.plot(thresholds, efficiency, label="Efficiency") # If necessary, make an inset plot if inset: # Use a zoom of five, place in lower left corner, pad border by 3 axins = zoomed_inset_axes(ax, zoom=5, loc=4, borderpad=3) axins.plot(thresholds, purity) axins.plot(thresholds, efficiency) # Set limits for inset plot axins.set_xlim(0.9, 1) axins.set_ylim(0.9, 1) # Set ticks for inset plot axins.set_xticks([0.9, 0.95, 1.0]) axins.set_yticks([0.9, 0.95, 1.0]) # Mark inset box mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") ax.set_xlabel("Confidence Cut") ax.set_ylabel("Quality Parameter") ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.legend(bbox_to_anchor=(0.5, 1), loc="lower center", ncol=2, frameon=False) if savepath is None: plt.show() else: plt.savefig(savepath)
def make_figure_8_plot(logfile): """Generate high quality plot of data to reproduce figure 8. The logfile is a CSV of the format [congestion_control, loss_rate, goodput, rtt, capacity, specified_bw] """ results = {} plt.figure() cubic = {"loss": [], "goodput": []} bbr = {"loss": [], "goodput": []} # For available options on plot() method, see: https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot # We prefer to use explicit keyword syntax to help code readability. # Create a figure. fig_width = 8 fig_height = 5 fig, axes = plt.subplots(figsize=(fig_width, fig_height)) results = parse_results_csv(logfile) xmark_ticks = get_loss_percent_xmark_ticks(results) cubic = results['cubic'] bbr = results['bbr'] debug_print_verbose("CUBIC: %s" % cubic) debug_print_verbose("BBR: %s" % bbr) matplotlib.rcParams.update({'figure.autolayout': True}) plt.plot(cubic['loss'], cubic['goodput'], color='blue', linestyle='solid', marker='o', markersize=7, label='CUBIC') plt.plot(bbr['loss'], bbr['goodput'], color='red', linestyle='solid', marker='x', markersize=7, label='BBR') # Plot ideal line of (1-lossRate * BW) ideal = {} ideal['loss'] = cubic['loss'] ideal['goodput'] = [(1 - (x / 100.0)) * 100 for x in ideal['loss']] plt.plot(ideal['loss'], ideal['goodput'], color='black', linestyle='dotted', label='ideal') plt.xscale('log') plot_titles(plt, xaxis="Loss Rate (%) - Log Scale", yaxis="Goodput (Mbps)") apply_axes_formatting(axes, deduplicate_xmark_ticks(xmark_ticks)) plot_legend(plt, axes, ncol=3) save_figure(plt, name="figures/figure8.png")
def set_font(self, font_dict=None): """ Set the font and font properties. Parameters ---------- font_dict : dict A dict of keyword parameters to be passed to :class:`matplotlib.font_manager.FontProperties`. Possible keys include: * family - The font family. Can be serif, sans-serif, cursive, 'fantasy', or 'monospace'. * style - The font style. Either normal, italic or oblique. * color - A valid color string like 'r', 'g', 'red', 'cobalt', and 'orange'. * variant - Either normal or small-caps. * size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12 * stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded * weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black See the matplotlib font manager API documentation for more details. http://matplotlib.org/api/font_manager_api.html Notes ----- Mathtext axis labels will only obey the `size` and `color` keyword. Examples -------- This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face. >>> prof = ProfilePlot(ds.all_data(), 'density', 'temperature') >>> slc.set_font({'family':'sans-serif', 'style':'italic', ... 'weight':'bold', 'size':24, 'color':'blue'}) """ from matplotlib.font_manager import FontProperties if font_dict is None: font_dict = {} if 'color' in font_dict: self._font_color = font_dict.pop('color') # Set default values if the user does not explicitly set them. # this prevents reverting to the matplotlib defaults. font_dict.setdefault('family', 'stixgeneral') font_dict.setdefault('size', 18) self._font_properties = \ FontProperties(**font_dict) return self
def set_font(self, font_dict=None): """ Set the font and font properties. Parameters ---------- font_dict : dict A dict of keyword parameters to be passed to :class:`matplotlib.font_manager.FontProperties`. Possible keys include: * family - The font family. Can be serif, sans-serif, cursive, 'fantasy' or 'monospace'. * style - The font style. Either normal, italic or oblique. * color - A valid color string like 'r', 'g', 'red', 'cobalt', and 'orange'. * variant - Either normal or small-caps. * size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12 * stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded * weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black See the matplotlib font manager API documentation for more details. http://matplotlib.org/api/font_manager_api.html Notes ----- Mathtext axis labels will only obey the `size` and `color` keyword. Examples -------- This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face. >>> slc = SlicePlot(ds, 'x', 'Density') >>> slc.set_font({'family':'sans-serif', 'style':'italic', ... 'weight':'bold', 'size':24, 'color':'blue'}) """ from matplotlib.font_manager import FontProperties if font_dict is None: font_dict = {} if 'color' in font_dict: self._font_color = font_dict.pop('color') # Set default values if the user does not explicitly set them. # this prevents reverting to the matplotlib defaults. font_dict.setdefault('family', 'stixgeneral') font_dict.setdefault('size', 18) self._font_properties = \ FontProperties(**font_dict) return self
def _get_axes_unit_labels(self, unit_x, unit_y): axes_unit_labels = ['', ''] comoving = False hinv = False for i, un in enumerate((unit_x, unit_y)): unn = None if hasattr(self.data_source, 'axis'): if hasattr(self.ds.coordinates, "image_units"): # This *forces* an override unn = self.ds.coordinates.image_units[ self.data_source.axis][i] elif hasattr(self.ds.coordinates, "default_unit_label"): axax = getattr(self.ds.coordinates, "%s_axis" % ("xy"[i]))[self.data_source.axis] unn = self.ds.coordinates.default_unit_label.get( axax, None) if unn is not None: axes_unit_labels[i] = r'\ \ \left('+unn+r'\right)' continue # Use sympy to factor h out of the unit. In this context 'un' # is a string, so we call the Unit constructor. expr = Unit(un, registry=self.ds.unit_registry).expr h_expr = Unit('h', registry=self.ds.unit_registry).expr # See http://docs.sympy.org/latest/modules/core.html#sympy.core.expr.Expr h_power = expr.as_coeff_exponent(h_expr)[1] # un is now the original unit, but with h factored out. un = str(expr*h_expr**(-1*h_power)) un_unit = Unit(un, registry=self.ds.unit_registry) cm = Unit('cm').expr if str(un).endswith('cm') and cm not in un_unit.expr.atoms(): comoving = True un = un[:-2] # no length units besides code_length end in h so this is safe if h_power == -1: hinv = True elif h_power != 0: # It doesn't make sense to scale a position by anything # other than h**-1 raise RuntimeError if un not in ['1', 'u', 'unitary']: if un in formatted_length_unit_names: un = formatted_length_unit_names[un] else: un = Unit(un, registry=self.ds.unit_registry) un = un.latex_representation() if hinv: un = un + '\,h^{-1}' if comoving: un = un + '\,(1+z)^{-1}' pp = un[0] if pp in latex_prefixes: symbol_wo_prefix = un[1:] if symbol_wo_prefix in prefixable_units: un = un.replace( pp, "{"+latex_prefixes[pp]+"}", 1) axes_unit_labels[i] = '\ \ ('+un+')' return axes_unit_labels
def nicecolorbar(self, axcb=None, reflevel=None, label=None, vmax=None, vmin=None, data=None, loc='head right', fontsize=8, ticks = None): if not axcb: axcb = matplotlib.pyplot.gca() divider = make_axes_locatable(axcb) # this code is from # http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axes-grid1 cax = divider.append_axes("right", size="2%", pad=0.15) levels = numpy.asarray([0.001,0.0025,0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,25,50,100,250,500,1000]) if vmax!= None and vmin != None: level = levels[numpy.nanargmin(abs((vmax - vmin)/5 - levels))] ticks = numpy.arange(vmin, vmax, level) elif vmax : level = levels[numpy.nanargmin(abs((vmax - numpy.nanmin(data))/5 - levels))] ticks = numpy.arange(numpy.nanmin(data), vmax, level) elif data is not None: level = None #levels[numpy.nanargmin(abs((numpy.nanmax(data) - numpy.nanmin(data))/5 - levels))] ticks = None #numpy.arange(numpy.nanmin(data), numpy.nanmax(data), level) #ticks -= numpy.nanmin(abs(ticks)) cb = matplotlib.pyplot.colorbar(self, cax=cax, label=label, orientation='vertical', extend='both', spacing='uniform', ticks=ticks) if vmax!= None and vmin != None: #print(ticks,vmin,vmax) cb.set_clim(vmin, vmax) cb.ax.yaxis.set_ticks_position('right') cb.ax.yaxis.set_label_position('right') cb.ax.set_yticklabels(cb.ax.get_yticklabels(), rotation='vertical',fontsize=fontsize) #if reflevel: # cb.ax.axhline((reflevel-min(cb.get_clim()))/numpy.diff(cb.get_clim()),zorder=999,color='k',linewidth=2) return cb