def _init_toolbar(self):
xmin, xmax = self.canvas.figure.bbox.intervalx
height, width = 50, xmax-xmin
Tk.Frame.__init__(self, master=self.window,
width=int(width), height=int(height),
borderwidth=2)
self.update() # Make axes menu
for text, tooltip_text, image_file, callback in self.toolitems:
if text is None:
# spacer, unhandled in Tk
pass
else:
button = self._Button(text=text, file=image_file,
command=getattr(self, callback))
if tooltip_text is not None:
ToolTip.createToolTip(button, tooltip_text)
self.message = Tk.StringVar(master=self)
self._message_label = Tk.Label(master=self, textvariable=self.message)
self._message_label.pack(side=Tk.RIGHT)
self.pack(side=Tk.BOTTOM, fill=Tk.X)
python类figure()的实例源码
def changeBackground(self,i):
#self.ColorBar = None
self.recallProjection = True
if i == 0:
self.background = None
self.clear = True
#self.axes1[self.slbplt.pNum-1] = None
#self.slbplt.figure.clear()
elif i == 1:
self.background = '.bluemarble'
elif i == 2:
self.background = '.shadedrelief'
else:
self.background = '.etopo'
self.calTimeRange = False
self.pltFxn(self.pNum)
def resetMapBoundaries(self):
self.mapBoundary.close()
self.userGrid = True
self.south = None
self.west = None
self.north = None
self.east = None
self.recallProjection = True
self.figure.clear()
self.ColorBar = None
self.cs = None
self.cs2 = None
self.barbs = None
self.vectors = None
self.vectorkey = None
self.cs2label = None
self.domain_average = None
self.coasts = None
self.countries = None
self.states = None
self.counties = None
self.meridians = None
self.parallels = None
self.calTimeRange = False
self.pltFxn(self.pNum)
def __init__(self, plotobj, line):
self.plotObj = plotobj
self.points = 0
self.marker = None
self.markerEvent = None
self.startMark = None
self.visible = False
self.line = line
self.userSelects = []
self.numSelection = 0
self.mode = 'None'
self.modeDefs = {'s':'Select', 'S':'Select','d':'Delete','D':'Delete',
'v':'View','V': 'View', 'm': 'Marker', 'escape': 'None'}
self.subMode = 'None'
self.subModeDefs = {'l':'Line', 'L':'Line','p':'Polygon','P':'Polygon'}
#self.xs = list(line.get_xdata())
#self.ys = list(line.get_ydata())
self.xs = []
self.ys = []
#print('init',self.xs)
print("data selector")
line.figure.canvas.setFocusPolicy( Qt.ClickFocus )
line.figure.canvas.setFocus()
#self.cid = line.figure.canvas.mpl_connect('button_press_event',self)
self.cid = line.figure.canvas.mpl_connect('key_press_event', self.keyPress)
def __call__(self, event):
if event.inaxes!=self.line.axes: return
if (self.mode == 'None'):
if event.key in self.modeDefs:
self.mode = self.modeDefs[event.key]
print('Mode = ',self.mode)
if(self.mode == 'Select'):
if(event.button == 3 ):
print("Erasing line")
self.clearSelect()
else:
if(event.dblclick ):
self.endLine(event)
else:
self.addToLine(event)
self.line.figure.canvas.draw()
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 getfigs(*fig_nums):
"""Get a list of matplotlib figures by figure numbers.
If no arguments are given, all available figures are returned. If the
argument list contains references to invalid figures, a warning is printed
but the function continues pasting further figures.
Parameters
----------
figs : tuple
A tuple of ints giving the figure numbers of the figures to return.
"""
from matplotlib._pylab_helpers import Gcf
if not fig_nums:
fig_managers = Gcf.get_all_fig_managers()
return [fm.canvas.figure for fm in fig_managers]
else:
figs = []
for num in fig_nums:
f = Gcf.figs.get(num)
if f is None:
print('Warning: figure %s not available.' % num)
else:
figs.append(f.canvas.figure)
return figs
def refreshFigure(self):
x=[]
y=[]
if self.lb_coords.size()==0:
pass
else:
coords_raw = self.lb_coords.get(0,tk.END)
for line in coords_raw:
coords = line.split(',')
x.append(float(coords[0]))
y.append(float(coords[1]))
self.line1.set_data(x,y)
ax = self.canvas.figure.axes[0]
ax.set_xlim(min(x)-0.5, max(x)+0.5)
ax.set_ylim(min(y)-0.5, max(y)+0.5)
self.canvas.draw()
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 getfigs(*fig_nums):
"""Get a list of matplotlib figures by figure numbers.
If no arguments are given, all available figures are returned. If the
argument list contains references to invalid figures, a warning is printed
but the function continues pasting further figures.
Parameters
----------
figs : tuple
A tuple of ints giving the figure numbers of the figures to return.
"""
from matplotlib._pylab_helpers import Gcf
if not fig_nums:
fig_managers = Gcf.get_all_fig_managers()
return [fm.canvas.figure for fm in fig_managers]
else:
figs = []
for num in fig_nums:
f = Gcf.figs.get(num)
if f is None:
print('Warning: figure %s not available.' % num)
else:
figs.append(f.canvas.figure)
return figs
def update(self, title=None, color=None, fontsize=10):
"""
Update PlotLabelTitle properties.
Parameters
----------
title : str
Title string.
bcolor : mpl color spec
Tiles's background color.
"""
if title is not None:
self._text.set_text(title)
if color is not None:
self.figure.set_facecolor(color)
if fontsize is not None:
self._text.set_fontsize(fontsize)
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, parent_window):
# Topic Names.
self.topic_names = self.get_topic_names()
self.main_label = Label(parent_window, text="RTK Fix Plot", font="Times 14 bold")
self.main_label.grid(row=0, columnspan=2)
# Plot for RTK fix.
self.first_receiver_state_received = False
self.first_time_receiver_state = 0
self.figure = Figure(figsize=(figureSizeWidth, figureSizeHeight), dpi=75)
self.axes_rtk_fix = self.figure.add_subplot(111)
self.axes_rtk_fix.set_xlabel('Time [s]')
self.axes_rtk_fix.set_ylabel('RTK Fix')
self.axes_rtk_fix.grid()
self.figure.tight_layout()
self.axes_rtk_fix.set_yticks([0.0, 1.0])
self.canvas = FigureCanvasTkAgg(self.figure, master=parent_window)
self.canvas.show()
self.canvas.get_tk_widget().grid(rowspan=4, columnspan=2)
# Position data.
self.odometry_msg_count = 0
self.time_rtk_fix = deque([], maxlen=maxLengthDequeArray)
self.rtk_fix = deque([], maxlen=maxLengthDequeArray)
self.line_rtk_fix = []
# Subscribe to topics.
rospy.Subscriber(self.topic_names['piksi_receiver_state'], ReceiverState,
self.receiver_state_callback)
def reset_view_handler(self):
if not self.first_odometry_received:
# Init subplots.
self.axes_position = self.figure.add_subplot(211)
self.axes_velocity = self.figure.add_subplot(212)
else:
# Clear subplots.
self.axes_position.clear()
self.axes_velocity.clear()
# Position.
self.axes_position.set_xlabel('Time [s]')
self.axes_position.set_ylabel('Position [m]')
self.axes_position.grid()
# Velocity.
self.axes_velocity.set_xlabel('Time [s]')
self.axes_velocity.set_ylabel('Velocity [m/s]')
self.axes_velocity.grid()
# Position data.
self.odometry_msg_count = 0
self.time_odometry = deque([], maxlen=maxLengthDequeArray)
self.x = deque([], maxlen=maxLengthDequeArray)
self.y = deque([], maxlen=maxLengthDequeArray)
self.z = deque([], maxlen=maxLengthDequeArray)
self.line_x = []
self.line_y = []
self.line_z = []
# Velocity data.
self.vx = deque([], maxlen=maxLengthDequeArray)
self.vy = deque([], maxlen=maxLengthDequeArray)
self.vz = deque([], maxlen=maxLengthDequeArray)
self.line_vx = []
self.line_vy = []
self.line_vz = []
self.reset_plot_view = True
def plot(self, ax, power=None, colormap="jet"):
"""
Plot the 2D power spectrum with EoR window marked on.
"""
x = self.k_perp
y = self.k_los
y_wedge = self.wedge_edge()
if power is None:
title = "EoR Window (fov=%.1f[deg], e=%.1f)" % (self.fov, self.e)
else:
title = (r"fov=%.1f[deg], e=%.1f, power=%.4e$\pm$%.4e[%s]" %
(self.fov, self.e, power[0], power[1], self.power_unit))
# data
mappable = ax.pcolormesh(x[1:], y[1:],
np.log10(self.ps2d[1:, 1:]),
cmap=colormap)
# EoR window
ax.axvline(x=self.k_perp_min, color="black",
linewidth=2, linestyle="--")
ax.axvline(x=self.k_perp_max, color="black",
linewidth=2, linestyle="--")
ax.axhline(y=self.k_los_min, color="black",
linewidth=2, linestyle="--")
ax.axhline(y=self.k_los_max, color="black",
linewidth=2, linestyle="--")
ax.plot(x, y_wedge, color="black", linewidth=2, linestyle="--")
#
ax.set(xscale="log", yscale="log",
xlim=(x[1], x[-1]), ylim=(y[1], y[-1]),
xlabel=r"$k_{\perp}$ [Mpc$^{-1}$]",
ylabel=r"$k_{||}$ [Mpc$^{-1}$]",
title=title)
cb = ax.figure.colorbar(mappable, ax=ax, pad=0.01, aspect=30)
cb.ax.set_xlabel("[%s]" % self.unit)
return ax
def plot(self, ax, ax_err, colormap="jet"):
"""
Plot the calculated 2D power spectrum.
"""
x = self.k_perp
y = self.k_los
if self.meanstd:
title = "2D Power Spectrum (mean)"
title_err = "Error (standard deviation)"
else:
title = "2D Power Spectrum (median)"
title_err = "Error (1.4826*MAD)"
# median/mean
mappable = ax.pcolormesh(x[1:], y[1:],
np.log10(self.ps2d[0, 1:, 1:]),
cmap=colormap)
vmin, vmax = mappable.get_clim()
ax.set(xscale="log", yscale="log",
xlim=(x[1], x[-1]), ylim=(y[1], y[-1]),
xlabel=r"$k_{\perp}$ [Mpc$^{-1}$]",
ylabel=r"$k_{||}$ [Mpc$^{-1}$]",
title=title)
cb = ax.figure.colorbar(mappable, ax=ax, pad=0.01, aspect=30)
cb.ax.set_xlabel(r"[%s$^2$ Mpc$^3$]" % self.unit)
# error
mappable = ax_err.pcolormesh(x[1:], y[1:],
np.log10(self.ps2d[1, 1:, 1:]),
cmap=colormap)
mappable.set_clim(vmin, vmax)
ax_err.set(xscale="log", yscale="log",
xlim=(x[1], x[-1]), ylim=(y[1], y[-1]),
xlabel=r"$k_{\perp}$ [Mpc$^{-1}$]",
ylabel=r"$k_{||}$ [Mpc$^{-1}$]",
title=title_err)
cb = ax_err.figure.colorbar(mappable, ax=ax_err, pad=0.01, aspect=30)
cb.ax.set_xlabel(r"[%s$^2$ Mpc$^3$]" % self.unit)
return (ax, ax_err)
def __init__(self, parent, columns, df_list_ctrl):
wx.Panel.__init__(self, parent)
columns_with_neutral_selection = [''] + list(columns)
self.columns = columns
self.df_list_ctrl = df_list_ctrl
self.figure = Figure(facecolor="white", figsize=(1, 1))
self.axes = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self, -1, self.figure)
chart_toolbar = NavigationToolbar2Wx(self.canvas)
self.combo_box1 = wx.ComboBox(self, choices=columns_with_neutral_selection, style=wx.CB_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.on_combo_box_select)
row_sizer = wx.BoxSizer(wx.HORIZONTAL)
row_sizer.Add(self.combo_box1, 0, wx.ALL | wx.ALIGN_CENTER, 5)
row_sizer.Add(chart_toolbar, 0, wx.ALL, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas, 1, flag=wx.EXPAND, border=5)
sizer.Add(row_sizer)
self.SetSizer(sizer)
def __init__(self, parent, columns, df_list_ctrl):
wx.Panel.__init__(self, parent)
columns_with_neutral_selection = [''] + list(columns)
self.columns = columns
self.df_list_ctrl = df_list_ctrl
self.figure = Figure(facecolor="white", figsize=(1, 1))
self.axes = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self, -1, self.figure)
chart_toolbar = NavigationToolbar2Wx(self.canvas)
self.combo_box1 = wx.ComboBox(self, choices=columns_with_neutral_selection, style=wx.CB_READONLY)
self.combo_box2 = wx.ComboBox(self, choices=columns_with_neutral_selection, style=wx.CB_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.on_combo_box_select)
row_sizer = wx.BoxSizer(wx.HORIZONTAL)
row_sizer.Add(self.combo_box1, 0, wx.ALL | wx.ALIGN_CENTER, 5)
row_sizer.Add(self.combo_box2, 0, wx.ALL | wx.ALIGN_CENTER, 5)
row_sizer.Add(chart_toolbar, 0, wx.ALL, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas, 1, flag=wx.EXPAND, border=5)
sizer.Add(row_sizer)
self.SetSizer(sizer)
def __init__(self, parent, plotdata, plotdata_files):
self.parent = parent
self.plots = plotdata # example: { "dgde" : { 0 : QPlotData_instance (from file 1), 1 : QPlotData_instance (from file 2) }, ... }, where 0,1,... are indices of the filenames in plotdata_files
self.plotdata_files = plotdata_files # [ "/home/.../pro/qa.PlotData.pickle", "/home/.../wat/qa.PlotData.pickle" ]
self.nrows = 1
self.ncols = 1
self.blocked_draw = False
self.subplot_lines = {}
self.COLORS_ACTIVE = ("#555555","#F75D59","#1589FF", "black", "red", "blue")
self.COLORS_INACTIVE = ("#aaaaaa","#F7bDb9","#a5a9FF", "#999999", "#FFaaaa", "#aaaaFF")
self.lb1_entries = ODict()
for plot_key, plot in self.plots.iteritems():
self.lb1_entries[ plot.values()[0].title ] = plot_key
self.lb1 = Tk.Listbox(self.parent, selectmode=Tk.EXTENDED, exportselection=0)
for plot_title in self.lb1_entries.keys():
self.lb1.insert(Tk.END, plot_title)
self.lb1.pack(fill=Tk.Y, side=Tk.LEFT)
self.lb2 = Tk.Listbox(self.parent, selectmode=Tk.EXTENDED, exportselection=0)
self.lb2.pack(fill=Tk.Y, side=Tk.LEFT)
self.figure = Figure(figsize=(5,4), dpi=100)
self.canvas = FigureCanvasTkAgg(self.figure, master=self.parent)
self.canvas.get_tk_widget().pack()
self.canvas._tkcanvas.pack(fill=Tk.BOTH, expand=1)
self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.parent )
self.toolbar.update()
self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
self.lb1.bind("<<ListboxSelect>>", self.on_select_lb1)
self.lb2.bind("<<ListboxSelect>>", self.on_select_lb2)
self.parent.bind("<Configure>", self.on_resize)
def draw_legend(self):
handls = []
labls = []
pos = "lower right"
for i, plotdata_file in enumerate(self.plotdata_files):
handls.append(mpatches.Patch(color=self.COLORS_ACTIVE[i]))
labls.append("%d: %s" % (i, plotdata_file))
self.figure.legend( handls, labls, pos, fontsize="xx-small" )
def run(self, fig):
"""
Run the exporter on the given figure
Parmeters
---------
fig : matplotlib.Figure instance
The figure to export
"""
# Calling savefig executes the draw() command, putting elements
# in the correct place.
fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi)
if self.close_mpl:
import matplotlib.pyplot as plt
plt.close(fig)
self.crawl_fig(fig)
def plot(self, cmap='seismic', vmin=-1.0, vmax=1.0):
"""
Plot contact matrix (requires matplotlib)
Parameters
----------
cmap : str
color map name, default 'seismic'
vmin : float
minimum value for color map interpolation; default -1.0
vmax : float
maximum value for color map interpolation; default 1.0
Returns
-------
fig : :class:`matplotlib.Figure`
matplotlib figure object for this plot
ax : :class:`matplotlib.Axes`
matplotlib axes object for this plot
"""
if not HAS_MATPLOTLIB: # pragma: no cover
raise RuntimeError("Error importing matplotlib")
norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
cmap_f = plt.get_cmap(cmap)
fig, ax = plt.subplots()
ax.axis([0, self.n_x, 0, self.n_y])
ax.set_facecolor(cmap_f(norm(0.0)))
for (pair, value) in self.counter.items():
pair_list = list(pair)
patch_0 = matplotlib.patches.Rectangle(
pair_list, 1, 1,
facecolor=cmap_f(norm(value)),
linewidth=0
)
patch_1 = matplotlib.patches.Rectangle(
(pair_list[1], pair_list[0]), 1, 1,
facecolor=cmap_f(norm(value)),
linewidth=0
)
ax.add_patch(patch_0)
ax.add_patch(patch_1)
return (fig, ax)
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 43
收藏 0
点赞 0
评论 0
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False,
**kwargs):
"""
Make a scatter plot from two DataFrame columns
Parameters
----------
data : DataFrame
x : Column name for the x-axis values
y : Column name for the y-axis values
ax : Matplotlib axis object
figsize : A tuple (width, height) in inches
grid : Setting this to True will show the grid
kwargs : other plotting keyword arguments
To be passed to scatter function
Returns
-------
fig : matplotlib.Figure
"""
import matplotlib.pyplot as plt
# workaround because `c='b'` is hardcoded in matplotlibs scatter method
kwargs.setdefault('c', plt.rcParams['patch.facecolor'])
def plot_group(group, ax):
xvals = group[x].values
yvals = group[y].values
ax.scatter(xvals, yvals, **kwargs)
ax.grid(grid)
if by is not None:
fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax)
else:
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
else:
fig = ax.get_figure()
plot_group(data, ax)
ax.set_ylabel(com.pprint_thing(y))
ax.set_xlabel(com.pprint_thing(x))
ax.grid(grid)
return fig