本文整理汇总了Python中matplotlib.patches.Rectangle类的典型用法代码示例。如果您正苦于以下问题:Python Rectangle类的具体用法?Python Rectangle怎么用?Python Rectangle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Rectangle类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: candlestick
def candlestick(self, axis, prices, width=0.5, colorup='green',
colordown='red', alpha=1.0):
"""
Plot the time, open, close, high, low as a vertical line ranging
from low to high. Use a rectangular bar to represent the
open-close span. If close >= open, use colorup to color the bar,
otherwise use colordown
ax : an Axes instance to plot to
width : fraction of a day for the rectangle width
colorup : the color of the rectangle where close >= open
colordown : the color of the rectangle where close < open
alpha : the rectangle alpha level
"""
dates = []
lines = []
for date in self.dates:
t = date2num(date)
close = prices.close[date]
open_ = prices.open[date]
if close >= open_:
color = colorup
lower = open_
height = close - open_
else:
color = colordown
lower = close
height = open_ - close
lines.extend([prices.low[date], prices.high[date], None])
dates.extend([t, t, None])
rect = Rectangle(xy=(t - width/2, lower), width=width,
height=height, facecolor=color, edgecolor=color, zorder=2)
rect.set_alpha(alpha)
axis.add_patch(rect)
axis.plot(dates, lines, linewidth=0.5, zorder=1, antialiased=True)
return min(y for y in lines if y is not None), max(lines)
开发者ID:pgwthf,项目名称:TSB,代码行数:35,代码来源:models.py
示例2: get_gate_patch
def get_gate_patch(self):
'''Returns a matplotlib patch to be drawn on the canvas whose dimensions
have been computed from the current gate.
'''
x_min, x_max = self.subplot.get_xlim()
x_range = x_max - x_min
y_min, y_max = self.subplot.get_ylim()
y_range = y_max - y_min
for subgate in self.gate.get_subgates():
col = subgate.get_column()
if col == self.x_column:
x_min = subgate.get_min()
x_range = subgate.get_max() - subgate.get_min()
if col == self.y_column:
y_min = subgate.get_min()
y_range = subgate.get_max() - subgate.get_min()
if self.patch not in self.subplot.patches:
rect = Rectangle((x_min, y_min), x_range, y_range, animated=True)
rect.set_fill(False)
rect.set_linestyle('dashed')
self.patch = self.subplot.add_patch(rect)
else:
self.patch.set_bounds(x_min, y_min, x_range, y_range)
return self.patch
开发者ID:CellProfiler,项目名称:CellProfiler-Analyst,代码行数:26,代码来源:gating.py
示例3: Canvas
class Canvas(object):
def __init__(self, img, name='misc', patch_size=(100, 100),
axes=None):
"""
Parameters
----------
img : 2-D ndarray
Image to crop from.
name : str
Basename of output files for images cropped from this canvas.
patch_size : tuple of ints
Size of the patch to crop (rows, cols).
axes : matplotlib axes object
Axes on which to draw the patch.
"""
self.name = name
self.img = img
self.x = 0
self.y = 0
self.patch_size = patch_size
h, w = self.patch_size
self.patch = Rectangle((self.x, self.y), h, w, alpha=0.3)
self.axes = axes
axes.add_patch(self.patch)
def paint(self):
self.patch.set_x(self.x)
self.patch.set_y(self.y)
# This is probably not the right call. Should call redraw on canvas?
plt.draw()
print self.name
开发者ID:Wichard-S,项目名称:supreme,代码行数:35,代码来源:mpl_cut.py
示例4: candlestick
def candlestick(ax, quotes, width=0.2, colorup="k", colordown="r", alpha=1.0):
OFFSET = width / 2.0
lines = []
patches = []
for q in quotes:
t, open, close, high, low = q[:5]
if close >= open:
color = colorup
lower = open
height = close - open
else:
color = colordown
lower = close
height = open - close
vline = Line2D(xdata=(t, t), ydata=(low, high), color=color, linewidth=0.5, antialiased=True)
rect = Rectangle(xy=(t - OFFSET, lower), width=width, height=height, facecolor=color, edgecolor=color)
rect.set_alpha(alpha)
lines.append(vline)
patches.append(rect)
ax.add_line(vline)
ax.add_patch(rect)
ax.autoscale_view()
return lines, patches
开发者ID:yhyan,项目名称:jq,代码行数:30,代码来源:stlib.py
示例5: plotKLine
def plotKLine(self, data, timescale=1.0,
width=0.9, colorup='r', colorflat = 'w', colordown='g', alpha=1.0):
self.priceChart.set_xlim(data[0]-50*timescale/86400,data[0]+8*timescale/86400)
t, open, close, high, low = data[:5]
if close > open:
color = colorup
elif close == open:
color = colorflat
else:
color = colordown
if close == open:
close = open + 0.005
shadowline = Line2D(xdata=(t, t), ydata=(low, high),
color=color,linewidth=0.5,antialiased=True,)
rect = Rectangle(xy = (t-width*timescale/172800, open),
width = width*timescale/86400,
height = close-open, facecolor=color, edgecolor=color,)
rect.set_alpha(alpha)
#self.priceChart.axhline(y=close,xmin=0.2,xmax=0.8)
self.priceChart.add_line(shadowline)
self.priceChart.add_patch(rect)
#返回画的图形,方便后面adjust
return shadowline, rect
开发者ID:fyabc,项目名称:DemoCTP,代码行数:32,代码来源:chartPlotter.py
示例6: plot_window
def plot_window(self, component, starttime, endtime, window_weight):
if component == "Z":
axis = self.plot_axis_z
elif component == "N":
axis = self.plot_axis_n
elif component == "E":
axis = self.plot_axis_e
else:
raise NotImplementedError
trace = self.data["synthetics"][0]
ymin, ymax = axis.get_ylim()
xmin = starttime - trace.stats.starttime
width = endtime - starttime
height = ymax - ymin
rect = Rectangle((xmin, ymin), width, height, facecolor="0.6",
alpha=0.5, edgecolor="0.5", picker=True)
axis.add_patch(rect)
attached_text = axis.text(
x=xmin + 0.02 * width, y=ymax - 0.02 * height,
s=str(window_weight), verticalalignment="top",
horizontalalignment="left", color="0.4", weight=1000)
# Monkey patch to trigger text removal as soon as the rectangle is
# removed.
def remove():
super(Rectangle, rect).remove()
attached_text.remove()
rect.remove = remove
开发者ID:seancug,项目名称:LASIF,代码行数:30,代码来源:misfit_gui.py
示例7: __plot_volume
def __plot_volume(self, ax, params=None):
if params is None:
width = 0.6
else:
width = params["width"]
prices = self.prices.tail(self.candlestick_num)
for i in self.indices:
p = prices.iloc[i, :]
open = p["Open"]
close = p["Close"]
volume = p["Volume"]
if close >= open:
color = "red"
else:
color = "green"
rect = Rectangle(
xy = (i - width/2, 0),
width = width,
height = volume,
facecolor = color,
edgecolor = color,
)
rect.set_alpha(0.5)
ax.add_patch(rect)
ax.set_ylim([0, prices["Volume"].max() * 1.25])
ax.grid(b=True, axis='x')
开发者ID:ss5211,项目名称:stockanalyzer,代码行数:30,代码来源:SymbolPlotter.py
示例8: __init__
def __init__(self, ax, labels, actives):
"""
Add check buttons to :class:`matplotlib.axes.Axes` instance *ax*
*labels*
A len(buttons) list of labels as strings
*actives*
A len(buttons) list of booleans indicating whether
the button is active
"""
ax.set_xticks([])
ax.set_yticks([])
ax.set_navigate(False)
if len(labels)>1:
dy = 1./(len(labels)+1)
ys = np.linspace(1-dy, dy, len(labels))
else:
dy = 0.25
ys = [0.5]
cnt = 0
axcolor = ax.get_axis_bgcolor()
self.labels = []
self.lines = []
self.rectangles = []
lineparams = {'color':'k', 'linewidth':1.25, 'transform':ax.transAxes,
'solid_capstyle':'butt'}
for y, label in zip(ys, labels):
t = ax.text(0.25, y, label, transform=ax.transAxes,
horizontalalignment='left',
verticalalignment='center')
w, h = dy/2., dy/2.
x, y = 0.05, y-h/2.
p = Rectangle(xy=(x,y), width=0.9, height=h, facecolor=axcolor,transform=ax.transAxes)
l1 = Rectangle(xy=(x,y), width=0.9, height=h, facecolor='red',alpha=0.5, transform=ax.transAxes)
l1.set_visible(actives[cnt])
#l2.set_visible(actives[cnt])
self.labels.append(t)
self.rectangles.append(p)
self.lines.append((l1))#,l2))
ax.add_patch(p)
ax.add_patch(l1)
#ax.add_line(l2)
cnt += 1
ax.figure.canvas.mpl_connect('button_press_event', self._clicked)
self.ax = ax
self.cnt = 0
self.observers = {}
开发者ID:smearedink,项目名称:tempy,代码行数:60,代码来源:_classes.py
示例9: create_artists
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
p = Rectangle(xy=(-xdescent, -ydescent),
width=width, height=height)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
开发者ID:JIE2016G,项目名称:matplotlib,代码行数:7,代码来源:legend_handler.py
示例10: addItem
def addItem(self, x, y, legend, shape, color, fill, overlay, z):
xView = numpy.array(x, copy=False)
yView = numpy.array(y, copy=False)
if shape == "line":
item = self.ax.plot(x, y, label=legend, color=color,
linestyle='-', marker=None)[0]
elif shape == "hline":
if hasattr(y, "__len__"):
y = y[-1]
item = self.ax.axhline(y, label=legend, color=color)
elif shape == "vline":
if hasattr(x, "__len__"):
x = x[-1]
item = self.ax.axvline(x, label=legend, color=color)
elif shape == 'rectangle':
xMin = numpy.nanmin(xView)
xMax = numpy.nanmax(xView)
yMin = numpy.nanmin(yView)
yMax = numpy.nanmax(yView)
w = xMax - xMin
h = yMax - yMin
item = Rectangle(xy=(xMin, yMin),
width=w,
height=h,
fill=False,
color=color)
if fill:
item.set_hatch('.')
self.ax.add_patch(item)
elif shape in ('polygon', 'polylines'):
xView = xView.reshape(1, -1)
yView = yView.reshape(1, -1)
item = Polygon(numpy.vstack((xView, yView)).T,
closed=(shape == 'polygon'),
fill=False,
label=legend,
color=color)
if fill and shape == 'polygon':
item.set_hatch('/')
self.ax.add_patch(item)
else:
raise NotImplementedError("Unsupported item shape %s" % shape)
item.set_zorder(z)
if overlay:
item.set_animated(True)
self._overlays.add(item)
return item
开发者ID:kif,项目名称:silx,代码行数:58,代码来源:BackendMatplotlib.py
示例11: __init__
def __init__(self, x, y, dx, dy, border_tol=0.1, resize=True, plotview=None, **opts):
shape = Rectangle((float(x),float(y)), float(dx), float(dy), **opts)
if 'linewidth' not in opts:
shape.set_linewidth(1.0)
if 'facecolor' not in opts:
shape.set_facecolor('r')
super(NXrectangle, self).__init__(shape, border_tol, resize, plotview)
self.shape.set_label('Rectangle')
self.rectangle = self.shape
开发者ID:nexpy,项目名称:nexpy,代码行数:9,代码来源:widgets.py
示例12: _get_emptiest_area
def _get_emptiest_area(ax, factor, target_x, areas_to_avoid=[]):
"""
Get's the emptiest area of size (1/factor x 1/factor) compared to the overall size of the plot area.
ax - the axes of the plot
factor - 1 / the fraction of the size the area should be
target_x - the ideal x-value for the area to be centred on
areas_to_avoid - a list of figure-space Rectangles which must be avoided
returns a Rectangle in figure-space which
"""
lines = ax.get_lines()
min_points = np.inf
min_rect = None
x_range = ax.get_xlim()
coord_width = x_range[1] - x_range[0]
plot_width = coord_width / factor
y_range = ax.get_ylim()
coord_height = y_range[1] - y_range[0]
plot_height = coord_height / factor
# Change the target x so that the centre will be at the target x
target_x -= plot_width / 2
if target_x < x_range[0]:
target_x = x_range[0]
# Start from the target x as an ideal position, then go right, then left
for i in np.concatenate([np.linspace(target_x, x_range[1] - plot_width, 10), np.linspace(target_x, x_range[0], 10)]):
# Start from the TOP of the plot as ideal, then downwards
for j in np.linspace(y_range[1] - plot_height, y_range[0], 10):
rect = Rectangle([i, j], plot_width, plot_height)
overlap = False
# Check that this rectangle will not overlap any of the explicitly-banned areas
rect_bbox = _coord_space_rect_to_figure_space_rect(rect, ax).get_bbox()
for area in areas_to_avoid:
if rect_bbox.overlaps(area.get_bbox()):
overlap = True
break
if overlap:
continue
points = 0
for line in lines:
for point in line.get_xydata():
if rect.contains_point(point, radius=0.0):
points += 1
if points < min_points:
min_points = points
min_rect = rect
if min_points == 0:
break
if min_points == 0:
break
return _coord_space_rect_to_figure_space_rect(min_rect, ax)
开发者ID:guygriffiths,项目名称:cci-visualisations,代码行数:57,代码来源:cci_timeseries.py
示例13: highlight_artist
def highlight_artist(self, val, artist=None):
# print val, artist
figure=self.get_figpage()._artists[0]
ax = self.get_figaxes()
if artist is None:
alist=self._artists
else:
alist=artist
if val == True:
container = self.get_container()
if container is None: return
de = self.get_data_extent()
from ifigure.matplotlib_mod.art3d_gl import AxesImageGL
if isinstance(alist[0], AxesImageGL):
hl = alist[0].add_hl_mask()
for item in hl:
alist[0].figobj_hl.append(item)
# hl = alist[0].make_hl_artist(container)
# rect_alpha = 0.0
else:
x=[de[0],de[1],de[1],de[0],de[0]]
y=[de[2],de[2],de[3],de[3],de[2]]
hl= container.plot(x, y, marker='s',
color='k', linestyle='None',
markerfacecolor='None',
markeredgewidth = 0.5,
scalex=False, scaley=False)
rect_alpha = 0.3
hlp = Rectangle((de[0],de[2]),
de[1]-de[0],
de[3]-de[2],
alpha=rect_alpha, facecolor='k',
figure = figure,
transform= container.transData)
if ax is not None:
x0, y0 = ax._artists[0].transAxes.transform((0,0))
x1, y1 = ax._artists[0].transAxes.transform((1,1))
bbox = Bbox([[x0,y0],[x1,y1]])
hlp.set_clip_box(bbox)
hlp.set_clip_on(True)
figure.patches.append(hlp)
for item in (hl[0], hlp):
alist[0].figobj_hl.append(item)
else:
for a in alist:
if len(a.figobj_hl) != 0:
a.figobj_hl[0].remove()
figure.patches.remove(a.figobj_hl[1])
a.figobj_hl=[]
开发者ID:piScope,项目名称:piScope,代码行数:54,代码来源:fig_image.py
示例14: __init__
def __init__(self, tgi, node, time, type, msg, fullmsg, fulltime):
Rectangle.__init__(self,
xy= (time + tgi.type_to_offset[type][0], \
node + tgi.type_to_offset[type][1]) , \
width=.5, height=.1, \
fc=tgi.type_to_color[type][0], \
ec=tgi.type_to_color[type][0], \
linewidth=0.0)
self.fulltime = fulltime
self.msg = msg
self.fullmsg = fullmsg
开发者ID:KPyda,项目名称:tinyos-2.x-contrib,代码行数:11,代码来源:mplwidgets.py
示例15: _on_figure_motion
def _on_figure_motion(self, event):
if event.inaxes == None:
return
self._motion_wait -= 1
if self._motion_wait > 0:
return
x0, y0, x1, y1 = event.inaxes.dataLim.bounds
number_of_points = len(event.inaxes.lines[-1].get_ydata())
index = int(round((number_of_points-1) * (event.xdata-x0)/x1))
if len(self._data[0]) < index + 1:
return
if self._background is None:
self._background = self._figure.canvas.copy_from_bbox(self._graphs[0].bbox)
# restore the clean slate background
self._figure.canvas.restore_region(self._background)
polygon = None
if self._select_start == None:
linev = self._graphs[-1].axvline(x=event.xdata, linewidth=1, color="#000000", alpha=0.5)
lineh = self._graphs[7].axhline(y=event.ydata, linewidth=1, color="#000000", alpha=0.5)
self._graphs[-1].draw_artist(linev)
self._graphs[-1].draw_artist(lineh)
else:
width = abs(event.xdata - self._select_start)
start = self._select_start
if (event.xdata < start):
start = event.xdata
if width < 20:
col = "#aa4444"
else:
col = "#888888"
polygon = Rectangle((start, 0), width, y1 + 10000, facecolor=col, alpha=0.5)
self._graphs[-1].add_patch(polygon)
self._graphs[-1].draw_artist(polygon)
self._figure.canvas.blit(self._graphs[-1].bbox)
if self._select_start == None:
linev.remove()
lineh.remove()
if polygon != None:
polygon.remove()
for i in xrange(0, 8):
if (i < 2):
val = str(self._data[i][index])
else:
val = str(int(self._data[i][index]))
self._mouse_texts[i].setText(val)
开发者ID:Lussarn,项目名称:vcontrol-log-analyzer,代码行数:54,代码来源:QTTelemetryWindow.py
示例16: _init_rectangles
def _init_rectangles(self):
self.rectangles = []
n_row = len(self.axes)
for row_i, all_axes in enumerate(self.axes):
self.rectangles.append([])
for col_i, axes in enumerate(all_axes):
rect = Rectangle( (0, 0), 0, 0 )
rect.set_visible(False)
axes.add_patch(rect)
self.rectangles[-1].append(rect)
return
开发者ID:cotterman,项目名称:Astro250_Python-for-Data-Scientists,代码行数:12,代码来源:brush_flower.py
示例17: on_press
def on_press(event):
global id_motion, xs, ys, r
print 'INAXES: ', event.inaxes
if event.inaxes!=ax: return
xs, ys = event.xdata, event.ydata
print 'PRESS button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
event.button, event.x, event.y, event.xdata, event.ydata)
r = Rectangle(xy=(xs,ys), height=0, width=0, fill=False, lw=2, alpha=0.2)
ax.add_artist(r)
r.set_clip_box(ax.bbox)
draw()
id_motion = fig.canvas.mpl_connect('motion_notify_event', on_motion)
开发者ID:chungjjang80,项目名称:FRETBursts,代码行数:12,代码来源:matplotlib_gui_select.py
示例18: PlotPatchLine
def PlotPatchLine(ax,prop):
length = ((prop['yEnd']-prop['yStart'])**2+(prop['zEnd']-prop['zStart'])**2) ** 0.5
ang = arctan((prop['zEnd']-prop['zStart'])/(prop['yEnd']-prop['yStart']))
ang = ang / 3.1415926*180
width = prop['widthLine']
patchi = Rectangle((prop['yStart'],prop['zStart']-width/2.0),length,width,color='blue',alpha=0.5)
t2 = matplotlib.transforms.Affine2D().rotate_deg(ang) + ax.transData
patchi.set_transform(t2)
ax.add_patch(patchi)
开发者ID:Junlings,项目名称:webfe,代码行数:12,代码来源:test_section.py
示例19: __plot_candlestick
def __plot_candlestick(self, ax, width=0.5, colorup='red', colordown='green', alpha=0.8):
offset = width / 2.0
line_width = width * 2
prices = self.prices.tail(self.candlestick_num)
for i in self.indices:
p = prices.iloc[i, :]
open = p["Open"]
close = p["Close"]
high = p["High"]
low = p["Low"]
box_high = max(open, close)
box_low = min(open, close)
height = box_high - box_low
if close >= open:
color = colorup
else:
color = colordown
vline_low = Line2D(
xdata=(i, i), ydata=(low, box_low),
color = 'black',
linewidth=line_width,
antialiased=True,
)
vline_high = Line2D(
xdata=(i, i), ydata=(box_high, high),
color = 'black',
linewidth=line_width,
antialiased=True,
)
rect = Rectangle(
xy = (i - offset, box_low),
width = width,
height = height,
facecolor = color,
edgecolor = color,
)
rect.set_alpha(alpha)
ax.add_line(vline_low)
ax.add_line(vline_high)
ax.add_patch(rect)
ax.autoscale_view()
开发者ID:ss5211,项目名称:stockanalyzer,代码行数:49,代码来源:SymbolPlotter.py
示例20: showBitPositions
def showBitPositions(self,ax,color=[0,0,255]):
color=[c/255. for c in color]
px,py,tx,ty=self.descriptor.getBits(self.cell)
truth=np.hstack((tx,ty))
for i,pos in enumerate(np.vstack((px,py))):
if truth[i]:
fc="r"
else:
fc="none"
xy=self.invTransForm([(pos[0]-0.5/self.scale),(pos[1]-0.5/self.scale)])
p = Rectangle(xy,width=self.descriptor.bitDistance/self.scale,height=-self.descriptor.bitDistance/self.scale,
fc=fc,lw=1,alpha=0.3)
t = MPLTransforms.Affine2D().rotate_around(xy[0],xy[1],-self.angle/180.*np.pi) + ax.transData
p.set_transform(t)
ax.add_artist(p)
开发者ID:drueffer,项目名称:apage_rom,代码行数:15,代码来源:autoDetect.py
注:本文中的matplotlib.patches.Rectangle类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论