Python matplotlib.figure 模块,Figure() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.figure.Figure()。
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
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)
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 create_plot_layout(self):
layout = QtGui.QVBoxLayout()
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.axes = self.fig.add_subplot(211)
self.axes.set_xlim(left = 0, right = 100)
self.axes.set_ylim(bottom = 0, top = 50)
self.thresholdLine = self.axes.axvline(self.thresholdVal, linewidth=3.0, color = 'r', label = 'Threshold')
self.axes.legend(loc = 'best')
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
self.axes.set_title('State Readout', fontsize = 22)
self.axes1 = self.fig.add_subplot(212)
self.axes1.set_xlim(left = 0, right = 10)
self.axes1.set_ylim(bottom = 0, top = 1.1)
self.fig.tight_layout()
layout.addWidget(self.mpl_toolbar)
layout.addWidget(self.canvas)
return layout
def get_training_image():
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import seaborn as sns
import StringIO
fig = Figure()
df = pd.DataFrame.from_dict(get_flattened_training_data())
features = [f for f in df.columns if f not in ['mac', 'location']]
df = df.rename(columns=dict(zip(features, [POWER_SLAVE_PREFIX + f for f in features])))
sns_plot = sns.pairplot(df, hue="location", vars=[POWER_SLAVE_PREFIX + f for f in features])
png_output = StringIO.StringIO()
sns_plot.savefig(png_output, format='png')
canvas = FigureCanvas(fig)
canvas.print_png(png_output)
print png_output.getvalue()
return
def makeGraph(self):
self.graphFigure = Figure(figsize=(1,0.1), dpi=50, facecolor="black")
self.subplot = self.graphFigure.add_subplot(1,1,1, facecolor=(0.3, 0.3, 0.3))
self.subplot.tick_params(axis="y", colors="grey", labelbottom="off", bottom="off")
self.subplot.tick_params(axis="x", colors="grey", labelbottom="off", bottom="off")
self.graphFigure.axes[0].get_xaxis().set_ticklabels([])
self.graphFigure.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
self.graphCanvas = FigureCanvasTkAgg(self.graphFigure, self)
self.graphCanvas.get_tk_widget().configure(bg="black")
self.graphCanvas.get_tk_widget().grid(row="2", column="2", columnspan="3", sticky="news")
yValues = self.mainWindow.characterDetector.playbackLogReader.logEntryFrequency
self.highestValue = 0
for value in yValues:
if value > self.highestValue: self.highestValue = value
self.subplot.plot(yValues, "dodgerblue")
self.timeLine, = self.subplot.plot([0, 0], [0, self.highestValue], "white")
#self.graphFigure.axes[0].set_xlim(0, len(yValues))
self.subplot.margins(0.005,0.01)
self.graphCanvas.show()
self.mainWindow.makeDraggable(self.graphCanvas.get_tk_widget())
def __init__(self, parent, settings, labelHandler, **kwargs):
tk.Frame.__init__(self, parent, **kwargs)
self.parent = parent
self.labelHandler = labelHandler
self.settings = settings
self.degree = 5
self.windowWidth = self.settings.getWindowWidth()
self.graphFigure = Figure(figsize=(4,2), dpi=100, facecolor="black")
self.subplot = self.graphFigure.add_subplot(1,1,1, facecolor=(0.3, 0.3, 0.3))
self.subplot.tick_params(axis="y", colors="grey", direction="in")
self.subplot.tick_params(axis="x", colors="grey", labelbottom="off", bottom="off")
self.graphFigure.axes[0].get_xaxis().set_ticklabels([])
self.graphFigure.subplots_adjust(left=(30/self.windowWidth), bottom=(15/self.windowWidth),
right=1, top=(1-15/self.windowWidth), wspace=0, hspace=0)
self.canvas = FigureCanvasTkAgg(self.graphFigure, self)
self.canvas.get_tk_widget().configure(bg="black")
self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
self.canvas.show()
def __init__(self, parent=None, width=5, height=4, dpi=80):
self.fig = Figure(figsize=(width, height), dpi=dpi)
super(PowerGraph, self).__init__(self.fig)
self.setParent(parent)
self.graph = self.fig.add_subplot(111)
self.clear()
self.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.fig.tight_layout()
self.draw()
# Update the graph using the given data
# 'times' should be datetime objects
# 'power' should be in Watts
def _build_image(data, cmap='gray'):
"""Build an image encoded in base64.
"""
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
figsize = data.shape[::-1]
if figsize[0] == 1:
figsize = tuple(figsize[1:])
data = data[:, :, 0]
fig = Figure(figsize=figsize, dpi=1.0, frameon=False)
FigureCanvas(fig)
cmap = getattr(plt.cm, cmap, plt.cm.gray)
fig.figimage(data, cmap=cmap)
output = BytesIO()
fig.savefig(output, dpi=1.0, format='png')
return base64.b64encode(output.getvalue()).decode('ascii')
def __init__(self, figure=None, parent=None, width=None, height=None, dpi=None):
if figure is not None:
self._figure = figure
else:
if width or height or dpi is None:
self._figure = Figure()
else:
self._figure = Figure(figsize=(width, height), dpi=dpi)
self._axes = self._figure.gca()
super(QMatplotlib, self).__init__(self._figure)
self.setParent(parent)
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
# self._set_size()
self.updateGeometry()
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self._allow_redraw = True
self._redraw_requested = False
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 setup_figure(self):
# Figure
fig = Figure((8.0, 6.0), dpi=90, facecolor=FIG_FACECOLOR)
canvas = FigureCanvas(fig)
canvas.setSizePolicy(
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding
)
canvas.setFocusPolicy( Qt.ClickFocus )
canvas.setFocus() # put last?
toolbar = NavigationToolbar(canvas, parent=self)
# Since we have only one plot, we can use add_axes
# instead of add_subplot, but then the subplot
# configuration tool in the navigation toolbar wouldn't
# work.
#
# self.axes = self.fig.add_subplot(111)
# self.axes = self.fig.axes
# Create the navigation toolbar, tied to the canvas
#
return fig, canvas, toolbar
# self.request_canvas_redraw()
def __init__(self, root, controller):
f = Figure()
ax = f.add_subplot(111)
ax.set_xticks([])
ax.set_yticks([])
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=None):
super(MplWidget, self).__init__(parent)
self.figure = Figure()
self.ax = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
self.cb = None
self.im = None
self.imsz = None
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 __loadMatplotlib(self):
global FigureCanvasTkAgg, Figure
if FigureCanvasTkAgg is None:
try:
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
except:
FigureCanvasTkAgg = Figure = False
def addPlot(
self,
title,
t, s,
row=None,
column=0,
colspan=0,
rowspan=0):
self.__verifyItem(self.n_plots, title, True)
self.__loadMatplotlib()
if FigureCanvasTkAgg is False:
raise Exception("Unable to load MatPlotLib - plots not available")
else:
fig = Figure()
axes = fig.add_subplot(111)
axes.plot(t,s)
canvas = FigureCanvasTkAgg(fig, self.__getContainer())
canvas.fig = fig
canvas.axes = axes
canvas.show()
# canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
self.__positionWidget(canvas.get_tk_widget(), row, column, colspan, rowspan)
self.n_plots[title] = canvas
return axes
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
# Use smaller labels
rcParams['axes.labelsize'] = 'small'
rcParams['xtick.labelsize'] = 'small'
rcParams['ytick.labelsize'] = 'small'
self.axes = fig.add_axes([0.15, 0.15, 0.85, 0.85])
FigureCanvas.__init__(self, fig)
self.setParent(parent)
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.setFocus()
fig.patch.set_alpha(0)
def init_ui(self, root):
self.figure = Figure(figsize=(5,5), dpi=100)
self.subplot = self.figure.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.figure, root)
self.canvas.show()
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(self.canvas, root)
toolbar.update()
def __init__(self, size=(5.0, 4.0), dpi=100):
QtGui.QWidget.__init__(self)
self.fig = Figure(size, dpi=dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.toolbar = NavigationToolbar(self.canvas, self)
self.vbox = QtGui.QVBoxLayout()
self.vbox.addWidget(self.toolbar)
self.vbox.addWidget(self.canvas)
self.setLayout(self.vbox)