def getFigureByXY(x,y):
ylabel='\nOutput, MBps'
fig = Figure(figsize=(16,6), dpi=120)
axis = fig.add_subplot(1, 1, 1)
axis.plot(x, y, color='#2b8ef9')
axis.fill_between(x,y, facecolor='#2b8ef9')
axis.grid(True)
axis.set_ylim(bottom=0)
axis.set_ylabel(ylabel)
# axis.set_xlabel('\n%s - %s' % (x[0],x[-1]))
axis.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))
axis.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,1)))
fig.autofmt_xdate()
fig.set_facecolor('white')
return fig
python类Figure()的实例源码
def plot_difference_histogram(group, gene_name, bins=np.arange(20.1)):
"""
Plot a histogram of percentage differences for a specific gene.
"""
exact_matches = group[group.V_SHM == 0]
CDR3s_exact = len(set(s for s in exact_matches.CDR3_nt if s))
Js_exact = len(set(exact_matches.J_gene))
fig = Figure(figsize=(100/25.4, 60/25.4))
ax = fig.gca()
ax.set_xlabel('Percentage difference')
ax.set_ylabel('Frequency')
fig.suptitle('Gene ' + gene_name, y=1.08, fontsize=16)
ax.set_title('{:,} sequences assigned'.format(len(group)))
ax.text(0.25, 0.95,
'{:,} ({:.1%}) exact matches\n {} unique CDR3\n {} unique J'.format(
len(exact_matches), len(exact_matches) / len(group),
CDR3s_exact, Js_exact),
transform=ax.transAxes, fontsize=10,
bbox=dict(boxstyle='round', facecolor='white', alpha=0.5),
horizontalalignment='left', verticalalignment='top')
_ = ax.hist(list(group.V_SHM), bins=bins)
return fig
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.configure(bg=BG_COLOR)
self.trends = Figure(figsize=(5, 5), dpi=100)
self.a = self.trends.add_subplot(111)
canvas = FigureCanvasTkAgg(self.trends, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1)
self.animation = FuncAnimation(self.trends, self.animate, 5000)
def __init__(self, parent):
fig = Figure(figsize=(4, 4), dpi=100, tight_layout=True)
super(DefaultGraph, self).__init__(fig)
self.setParent(parent)
sns.set(style="dark")
for index, s in zip(range(9), np.linspace(0, 3, 10)):
axes = fig.add_subplot(3, 3, index + 1)
x, y = np.random.randn(2, 50)
cmap = sns.cubehelix_palette(start=s, light=1, as_cmap=True)
sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=axes)
axes.set_xlim(-3, 3)
axes.set_ylim(-3, 3)
axes.set_xticks([])
axes.set_yticks([])
fig.suptitle("Activity Browser", y=0.5, fontsize=30, backgroundcolor=(1, 1, 1, 0.5))
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.updateGeometry()
def __init__(self, parent, mlca, width=6, height=6, dpi=100):
figure = Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
axes = figure.add_subplot(111)
super(LCAResultsPlot, self).__init__(figure)
self.setParent(parent)
activity_names = [format_activity_label(next(iter(f.keys()))) for f in mlca.func_units]
# From https://stanford.edu/~mwaskom/software/seaborn/tutorial/color_palettes.html
cmap = sns.cubehelix_palette(8, start=.5, rot=-.75, as_cmap=True)
hm = sns.heatmap(
# mlca.results / np.average(mlca.results, axis=0), # Normalize to get relative results
mlca.results,
annot=True,
linewidths=.05,
cmap=cmap,
xticklabels=["\n".join(x) for x in mlca.methods],
yticklabels=activity_names,
ax=axes,
square=False,
)
hm.tick_params(labelsize=8)
self.setMinimumSize(self.size())
# sns.set_context("notebook")
def __init__(self, parent, mlca, width=6, height=6, dpi=100):
figure = Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
axes = figure.add_subplot(121)
super(LCAProcessContributionPlot, self).__init__(figure)
self.setParent(parent)
method = 0 # TODO let user choose the LCIA method
tc = mlca.top_process_contributions(method=method, limit=5, relative=True)
df_tc = pd.DataFrame(tc)
df_tc.columns = [format_activity_label(a) for a in tc.keys()]
df_tc.index = [format_activity_label(a, style='pl') for a in df_tc.index]
plot = df_tc.T.plot.barh(
stacked=True,
figsize=(6, 6),
cmap=plt.cm.nipy_spectral_r,
ax=axes
)
plot.tick_params(labelsize=8)
axes.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.rc('legend', **{'fontsize': 8})
self.setMinimumSize(self.size())
def __init__(self, cpu_histogram):
super().__init__()
# set up the graphical elements
layout = QGridLayout(self)
self.setLayout(layout)
fig = Figure()
layout.addWidget(FigureCanvas(fig))
# do the plotting
ax = fig.add_subplot(1, 1, 1) # 1x1 grid, first subplot
ax.set_title('CPU Usage Histogram (%s Cores/%s Threads)' % (psutil.cpu_count(False), psutil.cpu_count(True)))
ax.set_ylabel('Count')
ax.set_xlabel('CPU %')
ax.grid(True)
xs = range(0, 101)
ax.plot(xs, [cpu_histogram[x] for x in xs])
ax.xaxis.set_major_locator(MultipleLocator(10.))
self.show()
def __init__(self, parent=None, width=5, height=4, dpi=100):
super(MatplotlibWidget, self).__init__(Figure())
# self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
self.setParent(parent)
self.figure = Figure(figsize=(width, height), dpi=dpi)
self.canvas = FigureCanvas(self.figure)
# FigureCanvas.setSizePolicy(self,
# QtGui.QSizePolicy.Expanding,
# QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.axes = self.figure.add_subplot(111)
self.setMinimumSize(self.size()*0.3)
print("---------------------- done")
def __init__(self, parent=None, width=5, height=4, dpi=100, numplots=1):
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = []
for n in range(numplots):
self.axes += [self.fig.add_subplot(100+10*(numplots)+n+1)]
self.axes[n].ticklabel_format(style='sci', axis='x', scilimits=(-3,3))
self.axes[n].ticklabel_format(style='sci', axis='y', scilimits=(-3,3))
self.traces = {}
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111, projection='3d')
super(View3D, self).__init__(fig)
self.setParent(parent)
self.axes.mouse_init()
super(View3D, self).setSizePolicy(
QSizePolicy.Expanding,
QSizePolicy.Expanding
)
super(View3D, self).updateGeometry()
self.segments_x = []
self.segments_y = []
self.segments_z = []
self.lines = {}
self.data = []
def __init__(self, number=None, title='', rows=1, columns=1, backend=Backends.WX_WIDGETS, *fa, **fk):
if number == Chart.AUTONUMBER:
Chart._serial += 1
number = Chart._serial
if rows < 1:
rows = 1
if columns < 1:
columns = 1
self._rows = int(rows)
self._columns = int(columns)
self._number = int(number)
self._title = str(title)
self._figure = Figure(*fa, **fk)
self._figure._figure_number = self._number
self._figure.suptitle(self._title)
self._beclass = backend
self._hasgui = False
self._plots = PlotsCollection(self._figure, self._rows, self._columns)
self._canvas = FigureCanvasAgg(self._figure)
formats = [ (f.upper(), f) for f in self._canvas.get_supported_filetypes() ]
self._formats = csb.core.Enum.create('OutputFormats', **dict(formats))
def createCanvas(self,parent,size=[1,1],titles=None,sup=None,proj=None,tight=False):
"""Create plot canvas."""
h=10000/self.dpi
v=10000/self.dpi
self.fig = Figure( dpi=self.dpi)
self.fig.set_size_inches(h,v,forward=True)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.currTab)
self.fig, self.axes = pyfrp_plot_module.makeSubplot(size,titles=titles,tight=tight,sup=sup,proj=proj,fig=self.fig)
self.ax=self.axes[0]
return self.fig,self.canvas,self.ax
def createCanvas(self,xlim=None,ylim=None):
h=500/self.dpi
v=500/self.dpi
self.fig = Figure( dpi=self.dpi)
self.fig.set_size_inches(h,v,forward=True)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.plotFrame)
self.ax = self.fig.add_subplot(111)
if xlim!=None:
self.ax.set_xlim(xlim)
if ylim!=None:
self.ax.set_ylim(ylim)
self.canvas.draw()
#self.plotFrame.adjustSize()
return
def plotbeamsigma(UC, diagnostics, s, sigx, sigy):
fig = Figure()
ax = fig.add_subplot(1, 1, 1)
rel = abs(nanmean(sigy)/nanmean(sigx))
if rel > 100 or rel < 1e-2:
drawlattice(ax, UC, diagnostics, [sigx], 0)
ax.plot(s, sigx, '-r', label=r'$\sigma_x$')
ax.plot([], [], '-b', label=r'$\sigma_y$')
ax.set_ylabel(r'Beam extent $\sigma_x$ / (m)')
ax.set_xlabel(r'orbit position s / (m)')
ax2 = ax.twinx()
ax2.plot(s, sigy, '-b')
ax2.tick_params(axis='y', colors='b')
ax2.set_ylabel(r'Beam extent $\sigma_y$ / (m)', color='b')
else:
drawlattice(ax, UC, diagnostics, [sigx, sigy], 0)
ax.plot(s, sigx, '-r', label=r'$\sigma_x$')
ax.plot(s, sigy, '-b', label=r'$\sigma_y$')
ax.set_xlabel(r'orbit position s / (m)')
ax.set_ylabel(r'Beam extent $\sigma_u$ / (m)')
ax.set_xlim([min(s), max(s)])
leg = ax.legend(fancybox=True, loc=2)
leg.get_frame().set_alpha(0.5)
return fig
def test_set_matplotlib_formats():
from matplotlib.figure import Figure
formatters = get_ipython().display_formatter.formatters
for formats in [
('png',),
('pdf', 'svg'),
('jpeg', 'retina', 'png'),
(),
]:
active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
display.set_matplotlib_formats(*formats)
for mime, f in formatters.items():
if mime in active_mimes:
nt.assert_in(Figure, f)
else:
nt.assert_not_in(Figure, f)
def test_select_figure_formats_kwargs():
ip = get_ipython()
kwargs = dict(quality=10, bbox_inches='tight')
pt.select_figure_formats(ip, 'png', **kwargs)
formatter = ip.display_formatter.formatters['image/png']
f = formatter.lookup_by_type(Figure)
cell = f.__closure__[0].cell_contents
nt.assert_equal(cell, kwargs)
# check that the formatter doesn't raise
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot([1,2,3])
plt.draw()
formatter.enabled = True
png = formatter(fig)
assert png.startswith(_PNG)
def make_figure_window(self):
self.figure_window = tk.Toplevel(self)
self.figure_window.wm_title('Preview')
screen_dpi = self.figure_window.winfo_fpixels('1i')
screen_width = self.figure_window.winfo_screenwidth() # in pixels
figure_width = screen_width / 2 / screen_dpi
figure_height = 0.75 * figure_width
self.figure = Figure(figsize=(figure_width, figure_height),
dpi=screen_dpi)
ax0 = self.figure.add_subplot(221)
axes = [self.figure.add_subplot(220 + i, sharex=ax0, sharey=ax0)
for i in range(2, 5)]
self.axes = np.array([ax0] + axes)
canvas = FigureCanvasTkAgg(self.figure, master=self.figure_window)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, self.figure_window)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def plot1(self, x, y, ticks, strlab, ID):
self.f = Figure(figsize=(3,4), dpi=100)
self.ax1 = self.f.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.f, master=root)
self.canvas.show()
self.canvas.get_tk_widget().grid(row = 0, column = 0, rowspan = 3, columnspan = 1, sticky = W+E+N+S)
self.ax1.set_xticklabels(ticks)
for tick in self.ax1.xaxis.get_major_ticks():
tick.label.set_fontsize(6)
# specify integer or one of preset strings, e.g.
#tick.label.set_fontsize('x-small')
tick.label.set_rotation(30)
if(strlab == "INT"):
self.ax1.set_title('Integral Graph: %s' % ID)
if(strlab == "FRQ"):
self.ax1.set_title('Frequency Graph: %s' % ID)
self.ax1.plot(x,y)
def plot2(self, x, y, ticks, strlab, ID):
self.f1 = Figure(figsize=(3,4), dpi=100)
self.ax2 = self.f1.add_subplot(111)
self.canvas4 = FigureCanvasTkAgg(self.f1, master=root)
self.canvas4.show()
self.canvas4.get_tk_widget().grid(row = 3, column = 0, rowspan = 3, columnspan = 1, sticky = W+E+N+S)
self.ax2.set_xticklabels(ticks)
for tick in self.ax2.xaxis.get_major_ticks():
tick.label.set_fontsize(6)
# specify integer or one of preset strings, e.g.
#tick.label.set_fontsize('x-small')
tick.label.set_rotation(30)
if(strlab == "INT"):
self.ax2.set_title('Integral Graph: %s' % ID)
if(strlab == "FRQ"):
self.ax2.set_title('Frequency Graph: %s' % ID)
self.ax2.plot(x,y)
# Search tree by ARB ID
def plot_telescope(self, outdir, figsize=(8, 8), dpi=150):
"""
Make plots showing all the telescope stations, central
stations, and core stations.
"""
if not has_matplotlib:
logger.error("matplotlib required to plot the telescope")
x, y = self.layouts_enu[:, 0], self.layouts_enu[:, 1]
# All stations
fpng = os.path.join(outdir, "layout_all.png")
fig = Figure(figsize=figsize, dpi=dpi)
FigureCanvas(fig)
ax = fig.add_subplot(111, aspect="equal")
ax.plot(x, y, "ko")
ax.grid()
ax.set_xlabel("East [m]")
ax.set_ylabel("North [m]")
ax.set_title("SKA1-low Stations Layout (All #%d)" % len(x))
fig.tight_layout()
fig.savefig(fpng)
logger.debug("Made plot for telescope all station: %s" % fpng)
# TODO...
def __init__(self, master = []):
self.master = master
# Erstellen des Fensters mit Rahmen und Canvas
self.figure = Figure(figsize = (7, 7), dpi = 100)
self.frame_c = Frame(relief = GROOVE, bd = 2)
self.frame_c.pack(fill = BOTH, expand = 1,)
self.canvas = FigureCanvasTkAgg(self.figure, master = self.frame_c)
self.canvas.show()
self.canvas.get_tk_widget().pack(fill = BOTH, expand = 1)
# Erstellen der Toolbar unten
self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frame_c)
self.toolbar.update()
self.canvas._tkcanvas.pack(fill = BOTH, expand = 1)
def __init__(self,master=[]):
self.master=master
#Erstellen des Fensters mit Rahmen und Canvas
self.figure = Figure(figsize=(7,7), dpi=100)
self.frame_c=Frame(relief = GROOVE,bd = 2)
self.frame_c.pack(fill=BOTH, expand=1,)
self.canvas = FigureCanvasTkAgg(self.figure, master=self.frame_c)
self.canvas.show()
self.canvas.get_tk_widget().pack(fill=BOTH, expand=1)
#Erstellen der Toolbar unten
self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frame_c)
self.toolbar.update()
self.canvas._tkcanvas.pack( fill=BOTH, expand=1)
def __init__(self,master=[]):
self.master=master
#Erstellen des Fensters mit Rahmen und Canvas
self.figure = Figure(figsize=(7,7), dpi=100)
self.frame_c=Frame(relief = GROOVE,bd = 2)
self.frame_c.pack(fill=BOTH, expand=1,)
self.canvas = FigureCanvasTkAgg(self.figure, master=self.frame_c)
self.canvas.show()
self.canvas.get_tk_widget().pack(fill=BOTH, expand=1)
#Erstellen der Toolbar unten
self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frame_c)
self.toolbar.update()
self.canvas._tkcanvas.pack( fill=BOTH, expand=1)
def __init__(self, parent, size=wx.Size(128,128), dpi=None, **kwargs):
self.size = size
self.dragging_curview_is_active = False
wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, size, 0, **kwargs)
self.ztv_frame = self.GetTopLevelParent()
self.figure = Figure(None, dpi)
self.axes = self.figure.add_axes([0., 0., 1., 1.])
self.curview_rectangle = Rectangle((0, 0), 1, 1, color='orange', fill=False, zorder=100)
self.axes.add_patch(self.curview_rectangle)
self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
self.overview_zoom_factor = 1.
self._SetSize()
self.set_xy_limits()
self.axes_widget = AxesWidget(self.figure.gca())
self.axes_widget.connect_event('button_press_event', self.on_button_press)
self.axes_widget.connect_event('button_release_event', self.on_button_release)
self.axes_widget.connect_event('motion_notify_event', self.on_motion)
pub.subscribe(self.redraw_overview_image, 'redraw-image')
pub.subscribe(self.redraw_box, 'primary-xy-limits-changed')
def __init__(self, parent, size=wx.Size(128,128), dpi=None, **kwargs):
self.size = size
self.dragging_curview_is_active = False
wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, size, 0, **kwargs)
self.ztv_frame = self.GetTopLevelParent()
self.figure = Figure(None, dpi)
self.axes = self.figure.add_axes([0., 0., 1., 1.])
self.curview_rectangle = Rectangle((0, 0), 1, 1, color='orange', fill=False, zorder=100)
self.axes.add_patch(self.curview_rectangle)
self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
self.overview_zoom_factor = 1.
self._SetSize()
self.set_xy_limits()
self.axes_widget = AxesWidget(self.figure.gca())
self.axes_widget.connect_event('button_press_event', self.on_button_press)
self.axes_widget.connect_event('button_release_event', self.on_button_release)
self.axes_widget.connect_event('motion_notify_event', self.on_motion)
pub.subscribe(self.redraw_overview_image, 'redraw-image')
pub.subscribe(self.redraw_box, 'primary-xy-limits-changed')
def initialize_display(self):
self.openButton = tk.Button(self, text = "Open File", command = self.get_filepath)
self.openButton.grid(row = 0, column = 0)
# This is just here to easily close the app during testing
self.quitButton = tk.Button(self, text = "Quit", command = self.quit)
self.quitButton.grid(row = 1, column = 0)
# testing alternative plotting solution
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)
canvas = FigureCanvasTkAgg(f, master=drawing_panel)
canvas.show()
# canvas.get_tk_widget().grid(row = 10, column = 10)
# canvas._tkcanvas.grid(row = 10, column = 10)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# toolbar = NavigationToolbar2TkAgg(canvas, root)
# toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def _write_fig(self, plots, fig_label):
fig = Figure()
ax = fig.add_subplot(111)
for i in xrange(len(plots)):
if plots[i].shape[0] != 2:
raise ValueError, "Attempting to plot matrix with row count other than 2"
if self.legend is not None:
ax.plot(plots[i][0], plots[i][1], self.colours.next(), label=self.legend[i])
else:
ax.plot(plots[i][0], plots[i][1], self.colours.next())
if self.legend is not None:
ax.legend(loc='best')
canvas = FigureCanvas(fig)
canvas.figure.savefig(new_filename(fig_label, 'figure', '.png'))
def __init__(self, root, controller):
f = Figure()
nticks = 10
ax = f.add_subplot(111, aspect='1')
ax.set_xticks([x*(x_max-x_min)/nticks+x_min for x in range(nticks+1)])
ax.set_yticks([y*(y_max-y_min)/nticks+y_min for y in range(1,nticks+1)])
ax.set_xlim((x_min, x_max))
ax.set_ylim((y_min, y_max))
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas.mpl_connect('button_press_event', self.onclick)
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
self.controllbar = ControllBar(root, controller)
self.f = f
self.ax = ax
self.canvas = canvas
self.controller = controller
self.contours = []
self.c_labels = None
self.plot_kernels()
def __init__(self, parent, plotNumber):
QWidget.__init__(self)
self.fig = Figure((4,1.5), dpi=100)
self.setMinimumSize(500,500)
self.canvas = FigureCanvas(self.fig)
self.setMouseTracking(False)
self.canvas.setParent(parent)
self.canvas.setMinimumSize(self.canvas.size())
boxTitleString = 'Plot # ' + str(plotNumber)
self.gbox = QGroupBox(boxTitleString,parent)
self.gbox.setStyleSheet(Layout.QGroupBox2())
plotLayout = QVBoxLayout()
plotLayout.addWidget(self.canvas)
self.mpl_toolbar = NavigationToolbar(self.canvas, parent)
plotLayout.addWidget(self.mpl_toolbar)
self.gbox.setLayout(plotLayout)
widgetLayout = QVBoxLayout()
widgetLayout.addWidget(self.gbox)
self.setLayout(widgetLayout)
def test_set_matplotlib_formats():
from matplotlib.figure import Figure
formatters = get_ipython().display_formatter.formatters
for formats in [
('png',),
('pdf', 'svg'),
('jpeg', 'retina', 'png'),
(),
]:
active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
display.set_matplotlib_formats(*formats)
for mime, f in formatters.items():
if mime in active_mimes:
nt.assert_in(Figure, f)
else:
nt.assert_not_in(Figure, f)