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)
python类Figure()的实例源码
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)