本文整理汇总了Python中matplotlib.collections.LineCollection.set_zorder方法的典型用法代码示例。如果您正苦于以下问题:Python LineCollection.set_zorder方法的具体用法?Python LineCollection.set_zorder怎么用?Python LineCollection.set_zorder使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.collections.LineCollection
的用法示例。
在下文中一共展示了LineCollection.set_zorder方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: colorbar_legend
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def colorbar_legend(ax, values, cmap, vis=True):
"""
Add a vertical colorbar legend to a plot
"""
x_range = ax.get_xlim()[1]-ax.get_xlim()[0]
y_range = ax.get_ylim()[1]-ax.get_ylim()[0]
x = [ax.get_xlim()[0]+x_range*0.05]
y = [ax.get_ylim()[1]-(y_range * 0.25), ax.get_ylim()[1]-(y_range*0.05)]
segs = []
vals=[]
p = (x[0], y[0]+((y[1]-y[0])/256.0))
for i in range(2, 257):
n = (x[0], y[0]+((y[1]-y[0])/256.0)*i)
segs.append((p, n))
p = segs[-1][-1]
vals.append(min(values)+((max(values)-min(values))/256.0)*(i-1))
lcbar = LineCollection(segs, cmap=cmap, lw=15)
lcbar.set_visible(vis)
lcbar.set_array(np.array(vals))
ax.add_collection(lcbar)
lcbar.set_zorder(1)
minlab = str(min(values))[:6]
maxlab = str(max(values))[:6]
ax.text(x[0]+x_range*.02, y[0], minlab, verticalalignment="bottom", visible=vis)
ax.text(x[0]+x_range*.02, y[1], maxlab, verticalalignment="top", visible=vis)
示例2: make_range_frame
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def make_range_frame(self):
xminf, xmaxf = data_bounds_on_axis(self.axes.viewLim.intervalx, self.xbounds)
yminf, ymaxf = data_bounds_on_axis(self.axes.viewLim.intervaly, self.ybounds)
xline = [(xminf, 0), (xmaxf, 0)]
yline = [(0, yminf), (0, ymaxf)]
range_lines = LineCollection(segments=[xline, yline], linewidths=[self.linewidth], colors=[self.color])
range_lines.set_transform(self.axes.transAxes)
range_lines.set_zorder(10)
return range_lines
示例3: _draw_arrows
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def _draw_arrows(self, G, pos, ax):
# Matplotlib's directed graph hack
# draw thick line segments at head end of edge
edge_pos = [(pos[n1], pos[n2]) for n1, n2 in self.G.edges()]
arrow_pos = self._calc_arrow_pos(edge_pos)
arrow_collection = LineCollection(arrow_pos,
colors = 'k',
linewidths = 4,
antialiaseds = (1,),
transOffset = ax.transData,
)
arrow_collection.set_zorder(1) # edges go behind nodes
ax.add_collection(arrow_collection)
return arrow_collection
示例4: show_localized
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def show_localized(net, estimated, scale=False, align=True,\
display_loc_err=True, show_labels=True):
"""
Display estimated positions.
estimated should be a list of dictionaries.
"""
from matplotlib.pylab import gca
from matplotlib.collections import LineCollection
truePos = Positions.create(net.pos)
estimated = Positions.create(estimated)
# copy estimated so that passed estimated remains unchanged
estimated = deepcopy(estimated)
if align:
# rotate, translate and if needed scale estimated w.r.t. true positions
align_clusters(truePos, estimated, scale)
#TODO: implement display of all subclusters
if len(estimated)>1:
raise(NotImplementedError)
else:
estimated_sc = estimated[0]
#net.show(positions=estimated_sc, show_labels=show_labels)
fig = net.get_fig(positions=estimated_sc, show_labels=show_labels)
ax = fig.gca()
minpos = min(estimated_sc.values(), axis=0)
maxpos = max(estimated_sc.values(), axis=0)
minpos -= (maxpos-minpos)*0.1
maxpos += (maxpos-minpos)*0.1
ax.set_xlim(minpos[0], maxpos[0])
ax.set_ylim(minpos[1], maxpos[1])
#fig.show()
if display_loc_err:
#TODO: not working in ipython notepad
ax = gca()
ax.set_title('Localized positions')
ax.set_title('Localization error display')
edge_pos = asarray([(net.pos[n], estimated_sc[n])
for n in estimated_sc.keys()])
errorCollection = LineCollection(edge_pos, colors='r',
transOffset=ax.transData)
errorCollection.set_zorder(1) # errors go behind nodes
ax.add_collection(errorCollection)
ax.figure.canvas.draw()
示例5: make_range_frame
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def make_range_frame (self):
rx = self.axes.get_xlim()
ry = self.axes.get_ylim()
px = pl.prctile ( self.x )
py = pl.prctile ( self.y )
if self.trim:
if px[2]-px[0]>1.5*(px[3]-px[1]):
px[0] = self.x[self.x>px[2]-1.5*(px[3]-px[1])].min()
if px[4]-px[2]>1.5*(px[3]-px[1]):
px[4] = self.x[self.x<px[2]+1.5*(px[3]-px[1])].min()
x = px-rx[0]
x /= rx[1]-rx[0]
y = py-ry[0]
y /= ry[1]-ry[0]
ex = .003
ey = .003
xline = [
[(x[0],0),(x[1],0)],
[(x[1],ey),(x[2]-ex,ey)],
[(x[2]+ex,ey),(x[3],ey)],
[(x[3],0),(x[4],0)]
]
yline = [
[(0,y[0]),(0,y[1])],
[(ex,y[1]),(ex,y[2]-ey)],
[(ex,y[2]+ey),(ex,y[3])],
[(0,y[3]),(0,y[4])]
]
widths = [1,1,1,1]
range_lines = LineCollection(
segments=pl.clip(xline+yline,0,1),
linewidths=widths+widths,
colors=[[0]*3]*2*len(widths) )
range_lines.set_transform ( self.axes.transAxes )
range_lines.set_zorder(10)
self.axes.get_xaxis().tick_bottom()
self.axes.get_yaxis().tick_left()
self.axes.set_xticks(px)
self.axes.set_yticks(py)
self.axes.tick_params ( width=0 )
return range_lines
示例6: make_box_plot
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def make_box_plot (self):
x = self.x
rx = self.axes.get_xlim()
ry = self.axes.get_ylim()
ex = self.offset*(rx[1]-rx[0])
ey = self.offset*(ry[1]-ry[0])
if self.vert == 1:
ex,ey = ey,ex
p = self.boxstats['main']
n = self.boxstats['notch']
f_lo,f_hi = self.boxstats['fliers']
if self.notch:
lines = [ [(x,p[0]),(x,p[1])],
[(x+ex,p[1]),(x+ex,n[0])],
[(x+ex,n[0]),(x-ex,p[2]-ey)],
[(x-ex,p[2]+ey),(x+ex,n[1])],
[(x+ex,n[1]),(x+ex,p[3])],
[(x,p[3]),(x,p[4])] ]
else:
lines = [ [(x,p[0]),(x,p[1])],
[(x+ex,p[1]),(x+ex,p[2]-ey)],
[(x+ex,p[2]+ey),(x+ex,p[3])],
[(x,p[3]),(x,p[4])] ]
lines = pl.array(lines)
if self.vert==1:
lines = pl.array([ pl.c_[l[:,1],l[:,0]] for l in lines ])
pt = self.axes.plot ( f_lo, [x]*len(f_lo), '.', color=self.color,
markersize=self.lw ) + \
self.axes.plot ( f_hi, [x]*len(f_hi), '.', color=self.color,
markersize=self.lw )
dummy = self.axes.plot ( [p[0],p[-1]],[x-ex,x+ex], '.', markersize=0 )
else:
pt = self.axes.plot ( [x]*len(f_lo), f_lo, '.', color=self.color,
markersize=1 ) + \
self.axes.plot ( [x]*len(f_hi), f_hi, '.', color=self.color,
markersize=1 )
dummy = self.axes.plot ( [x-ex,x+ex], [p[0],p[-1]], '.', markersize=0 )
box = LineCollection (
segments=lines,
linewidths=[self.lw]*lines.shape[0],
colors=[self.color]*lines.shape[0] )
box.set_transform ( self.axes.transData )
box.set_zorder(10)
return box, pt[0],dummy[0]
示例7: draw_networkx_edges
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
#.........这里部分代码省略.........
and cb.iterable(edge_color) \
and len(edge_color) == len(edge_pos):
if numpy.alltrue([cb.is_string_like(c)
for c in edge_color]):
# (should check ALL elements)
# list of color letters such as ['k','r','k',...]
edge_colors = tuple([colorConverter.to_rgba(c, alpha)
for c in edge_color])
elif numpy.alltrue([not cb.is_string_like(c)
for c in edge_color]):
# If color specs are given as (rgb) or (rgba) tuples, we're OK
if numpy.alltrue([cb.iterable(c) and len(c) in (3, 4)
for c in edge_color]):
edge_colors = tuple(edge_color)
else:
# numbers (which are going to be mapped with a colormap)
edge_colors = None
else:
raise ValueError('edge_color must consist of either color names or numbers')
else:
if cb.is_string_like(edge_color) or len(edge_color) == 1:
edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
else:
raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')
edge_collection = LineCollection(edge_pos,
colors=edge_colors,
linewidths=lw,
antialiaseds=(1,),
linestyle=style,
transOffset = ax.transData,
)
edge_collection.set_zorder(1) # edges go behind nodes
edge_collection.set_label(label)
ax.add_collection(edge_collection)
# Note: there was a bug in mpl regarding the handling of alpha values for
# each line in a LineCollection. It was fixed in matplotlib in r7184 and
# r7189 (June 6 2009). We should then not set the alpha value globally,
# since the user can instead provide per-edge alphas now. Only set it
# globally if provided as a scalar.
if cb.is_numlike(alpha):
edge_collection.set_alpha(alpha)
if edge_colors is None:
if edge_cmap is not None:
assert(isinstance(edge_cmap, Colormap))
edge_collection.set_array(numpy.asarray(edge_color))
edge_collection.set_cmap(edge_cmap)
if edge_vmin is not None or edge_vmax is not None:
edge_collection.set_clim(edge_vmin, edge_vmax)
else:
edge_collection.autoscale()
arrow_collection = None
if G.is_directed() and arrows:
# a directed graph hack
# draw thick line segments at head end of edge
# waiting for someone else to implement arrows that will work
arrow_colors = edge_colors
a_pos = []
p = 1.0-0.25 # make head segment 25 percent of edge length
for src, dst in edge_pos:
示例8: draw_networkx_edges
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
#.........这里部分代码省略.........
if np.alltrue([cb.iterable(c) and len(c) in (3,4)
for c in edge_color]):
edge_colors = tuple(edge_color)
alpha=None
else:
# numbers (which are going to be mapped with a colormap)
edge_colors = None
else:
raise ValueError('edge_color must consist of either color names or numbers')
else:
if len(edge_color)==1:
edge_colors = ( colorConverter.to_rgba(edge_color, alpha), )
else:
raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')
edge_collection = LineCollection(edge_pos,
colors = edge_colors,
linewidths = lw,
antialiaseds = (1,),
linestyle = style,
transOffset = ax.transData,
)
# Note: there was a bug in mpl regarding the handling of alpha values for
# each line in a LineCollection. It was fixed in matplotlib in r7184 and
# r7189 (June 6 2009). We should then not set the alpha value globally,
# since the user can instead provide per-edge alphas now. Only set it
# globally if provided as a scalar.
if cb.is_numlike(alpha):
edge_collection.set_alpha(alpha)
# need 0.87.7 or greater for edge colormaps. No checks done, this will
# just not work with an older mpl
if edge_colors is None:
if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap))
edge_collection.set_array(np.asarray(edge_color))
edge_collection.set_cmap(edge_cmap)
if edge_vmin is not None or edge_vmax is not None:
edge_collection.set_clim(edge_vmin, edge_vmax)
else:
edge_collection.autoscale()
pylab.sci(edge_collection)
arrow_collection=None
if G.is_directed() and arrows:
# a directed graph hack
# draw thick line segments at head end of edge
# waiting for someone else to implement arrows that will work
arrow_colors = ( colorConverter.to_rgba('k', alpha), )
a_pos=[]
p=1.0-0.25 # make head segment 25 percent of edge length
for src,dst in edge_pos:
x1,y1=src
x2,y2=dst
dx=x2-x1 # x offset
dy=y2-y1 # y offset
d=np.sqrt(float(dx**2+dy**2)) # length of edge
if d==0: # source and target at same position
continue
if dx==0: # vertical edge
xa=x2
ya=dy*p+y1
if dy==0: # horizontal edge
ya=y2
xa=dx*p+x1
else:
theta=np.arctan2(dy,dx)
xa=p*d*np.cos(theta)+x1
ya=p*d*np.sin(theta)+y1
a_pos.append(((xa,ya),(x2,y2)))
arrow_collection = LineCollection(a_pos,
colors = arrow_colors,
linewidths = [4*ww for ww in lw],
antialiaseds = (1,),
transOffset = ax.transData,
)
# update view
minx = np.amin(np.ravel(edge_pos[:,:,0]))
maxx = np.amax(np.ravel(edge_pos[:,:,0]))
miny = np.amin(np.ravel(edge_pos[:,:,1]))
maxy = np.amax(np.ravel(edge_pos[:,:,1]))
w = maxx-minx
h = maxy-miny
padx, pady = 0.05*w, 0.05*h
corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
ax.update_datalim( corners)
ax.autoscale_view()
edge_collection.set_zorder(1) # edges go behind nodes
ax.add_collection(edge_collection)
if arrow_collection:
arrow_collection.set_zorder(1) # edges go behind nodes
ax.add_collection(arrow_collection)
return edge_collection
示例9: plot
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
#.........这里部分代码省略.........
return tuple(xy1), tuple(xy2)
x = network.buses["x"]
y = network.buses["y"]
if basemap and basemap_present:
if boundaries is None:
(x1, y1), (x2, y2) = compute_bbox_with_margins(margin, x, y)
else:
x1, x2, y1, y2 = boundaries
bmap = Basemap(resolution='l', epsg=network.srid,
llcrnrlat=y1, urcrnrlat=y2, llcrnrlon=x1,
urcrnrlon=x2, ax=ax)
bmap.drawcountries()
bmap.drawcoastlines()
x, y = bmap(x.values, y.values)
x = pd.Series(x, network.buses.index)
y = pd.Series(y, network.buses.index)
c = pd.Series(bus_colors, index=network.buses.index)
if c.dtype == np.dtype('O'):
c.fillna("b", inplace=True)
s = pd.Series(bus_sizes, index=network.buses.index, dtype="float").fillna(10)
bus_collection = ax.scatter(x, y, c=c, s=s, cmap=bus_cmap)
def as_branch_series(ser):
if isinstance(ser, pd.Series):
if isinstance(ser.index, pd.MultiIndex):
return ser
index = ser.index
ser = ser.values
else:
index = network.lines.index
return pd.Series(ser,
index=pd.MultiIndex(levels=(["Line"], index),
labels=(np.zeros(len(index)),
np.arange(len(index)))))
line_colors = as_branch_series(line_colors)
line_widths = as_branch_series(line_widths)
if not isinstance(line_cmap, dict):
line_cmap = {'Line': line_cmap}
branch_collections = []
for t in network.iterate_components(branch_types):
l_defaults = defaults_for_branches[t.name]
l_widths = line_widths.get(t.name, l_defaults['width'])
l_nums = None
if t.name in line_colors:
l_colors = line_colors[t.name]
if issubclass(l_colors.dtype.type, np.number):
l_nums = l_colors
l_colors = None
else:
l_colors.fillna(l_defaults['color'], inplace=True)
else:
l_colors = l_defaults['color']
if not geometry:
segments = (np.asarray(((t.df.bus0.map(x),
t.df.bus0.map(y)),
(t.df.bus1.map(x),
t.df.bus1.map(y))))
.transpose(2, 0, 1))
else:
from shapely.wkt import loads
from shapely.geometry import LineString
linestrings = t.df.geometry.map(loads)
assert all(isinstance(ls, LineString) for ls in linestrings), \
"The WKT-encoded geometry in the 'geometry' column must be composed of LineStrings"
segments = np.asarray(list(linestrings.map(np.asarray)))
if basemap and basemap_present:
segments = np.transpose(bmap(*np.transpose(segments, (2, 0, 1))), (1, 2, 0))
l_collection = LineCollection(segments,
linewidths=l_widths,
antialiaseds=(1,),
colors=l_colors,
transOffset=ax.transData)
if l_nums is not None:
l_collection.set_array(np.asarray(l_nums))
l_collection.set_cmap(line_cmap.get(t.name, None))
l_collection.autoscale()
ax.add_collection(l_collection)
l_collection.set_zorder(1)
branch_collections.append(l_collection)
bus_collection.set_zorder(2)
ax.update_datalim(compute_bbox_with_margins(margin, x, y))
ax.autoscale_view()
ax.set_title(title)
return (bus_collection,) + tuple(branch_collections)
示例10: add_phylorate
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def add_phylorate(treeplot, rates, nodeidx, vis=True):
"""
Add phylorate plot generated from data analyzed with BAMM
(http://bamm-project.org/introduction.html)
Args:
rates (array): Array of rates along branches
created by r_funcs.phylorate
nodeidx (array): Array of node indices matching rates (also created
by r_funcs.phylorate)
WARNING:
Ladderizing the tree can cause incorrect assignment of Ape node index
numbers. To prevent this, call this function or root.ape_node_idx()
before ladderizing the tree to assign correct Ape node index numbers.
"""
if not treeplot.root.apeidx:
treeplot.root.ape_node_idx()
segments = []
values = []
if treeplot.plottype == "radial":
radpatches = [] # For use in drawing arcs for radial plots
for n in treeplot.root.descendants():
n.rates = rates[nodeidx==n.apeidx]
c = treeplot.n2c[n]
pc = treeplot._path_to_parent(n)[0][1]
xd = c.x - pc[0]
yd = c.y - pc[1]
xseg = xd/len(n.rates)
yseg = yd/len(n.rates)
for i, rate in enumerate(n.rates):
x0 = pc[0] + i*xseg
y0 = pc[1] + i*yseg
x1 = x0 + xseg
y1 = y0 + yseg
segments.append(((x0, y0), (x1, y1)))
values.append(rate)
curverts = treeplot._path_to_parent(n)[0][2:]
curcodes = treeplot._path_to_parent(n)[1][2:]
curcol = RdYlBu(n.rates[0])
radpatches.append(PathPatch(
Path(curverts, curcodes), lw=2, edgecolor = curcol,
fill=False))
else:
for n in treeplot.root.descendants():
n.rates = rates[nodeidx==n.apeidx]
c = treeplot.n2c[n]
pc = treeplot.n2c[n.parent]
seglen = (c.x-pc.x)/len(n.rates)
for i, rate in enumerate(n.rates):
x0 = pc.x + i*seglen
x1 = x0 + seglen
segments.append(((x0, c.y), (x1, c.y)))
values.append(rate)
segments.append(((pc.x, pc.y), (pc.x, c.y)))
values.append(n.rates[0])
lc = LineCollection(segments, cmap=RdYlBu, lw=2)
lc.set_array(np.array(values))
treeplot.add_collection(lc)
lc.set_zorder(1)
if treeplot.plottype == "radial":
arccol = matplotlib.collections.PatchCollection(radpatches,
match_original=True)
treeplot.add_collection(arccol)
arccol.set_visible(vis)
arccol.set_zorder(1)
lc.set_visible(vis)
colorbar_legend(treeplot, values, RdYlBu, vis=vis)
treeplot.figure.canvas.draw_idle()
示例11: draw_networkx_edges
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
#.........这里部分代码省略.........
and cb.iterable(edge_color) \
and len(edge_color) == len(edge_pos):
if np.alltrue([is_string_like(c) for c in edge_color]):
# (should check ALL elements)
# list of color letters such as ['k','r','k',...]
edge_colors = tuple([colorConverter.to_rgba(c, alpha)
for c in edge_color])
elif np.alltrue([not is_string_like(c) for c in edge_color]):
# If color specs are given as (rgb) or (rgba) tuples, we're OK
if np.alltrue([cb.iterable(c) and len(c) in (3, 4)
for c in edge_color]):
edge_colors = tuple(edge_color)
else:
# numbers (which are going to be mapped with a colormap)
edge_colors = None
else:
raise ValueError('edge_color must contain color names or numbers')
else:
if is_string_like(edge_color) or len(edge_color) == 1:
edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
else:
msg = 'edge_color must be a color or list of one color per edge'
raise ValueError(msg)
if (not G.is_directed() or not arrows):
edge_collection = LineCollection(edge_pos,
colors=edge_colors,
linewidths=lw,
antialiaseds=(1,),
linestyle=style,
transOffset=ax.transData,
)
edge_collection.set_zorder(1) # edges go behind nodes
edge_collection.set_label(label)
ax.add_collection(edge_collection)
# Note: there was a bug in mpl regarding the handling of alpha values
# for each line in a LineCollection. It was fixed in matplotlib by
# r7184 and r7189 (June 6 2009). We should then not set the alpha
# value globally, since the user can instead provide per-edge alphas
# now. Only set it globally if provided as a scalar.
if cb.is_numlike(alpha):
edge_collection.set_alpha(alpha)
if edge_colors is None:
if edge_cmap is not None:
assert(isinstance(edge_cmap, Colormap))
edge_collection.set_array(np.asarray(edge_color))
edge_collection.set_cmap(edge_cmap)
if edge_vmin is not None or edge_vmax is not None:
edge_collection.set_clim(edge_vmin, edge_vmax)
else:
edge_collection.autoscale()
return edge_collection
arrow_collection = None
if G.is_directed() and arrows:
# Note: Waiting for someone to implement arrow to intersection with
# marker. Meanwhile, this works well for polygons with more than 4
# sides and circle.
def to_marker_edge(marker_size, marker):
if marker in "s^>v<d": # `large` markers need extra space
return np.sqrt(2 * marker_size) / 2
示例12: draw_networkx_edges
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
#.........这里部分代码省略.........
if len(edge_color)==1:
edge_colors = ( colorConverter.to_rgba(edge_color, alpha), )
else:
raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')
edge_collection = LineCollection(edge_pos,
colors = edge_colors,
linewidths = lw,
antialiaseds = (1,),
linestyle = style,
transOffset = ax.transData,
)
edge_collection.set_alpha(alpha)
# need 0.87.7 or greater for edge colormaps
mpl_version=matplotlib.__version__
if mpl_version.endswith('svn'):
mpl_version=matplotlib.__version__[0:-3]
if mpl_version.endswith('pre'):
mpl_version=matplotlib.__version__[0:-3]
if map(int,mpl_version.split('.'))>=[0,87,7]:
if edge_colors is None:
if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap))
edge_collection.set_array(asarray(edge_color))
edge_collection.set_cmap(edge_cmap)
if edge_vmin is not None or edge_vmax is not None:
edge_collection.set_clim(edge_vmin, edge_vmax)
else:
edge_collection.autoscale()
matplotlib.pylab.sci(edge_collection)
# else:
# sys.stderr.write(\
# """matplotlib version >= 0.87.7 required for colormapped edges.
# (version %s detected)."""%matplotlib.__version__)
# raise UserWarning(\
# """matplotlib version >= 0.87.7 required for colormapped edges.
# (version %s detected)."""%matplotlib.__version__)
arrow_collection=None
if G.directed and arrows:
# a directed graph hack
# draw thick line segments at head end of edge
# waiting for someone else to implement arrows that will work
arrow_colors = ( colorConverter.to_rgba('k', alpha), )
a_pos=[]
p=1.0-0.25 # make head segment 25 percent of edge length
for src,dst in edge_pos:
x1,y1=src
x2,y2=dst
dx=x2-x1 # x offset
dy=y2-y1 # y offset
d=sqrt(float(dx**2+dy**2)) # length of edge
if d==0: # source and target at same position
continue
if dx==0: # vertical edge
xa=x2
ya=dy*p+y1
if dy==0: # horizontal edge
ya=y2
xa=dx*p+x1
else:
theta=arctan2(dy,dx)
xa=p*d*cos(theta)+x1
ya=p*d*sin(theta)+y1
a_pos.append(((xa,ya),(x2,y2)))
arrow_collection = LineCollection(a_pos,
colors = arrow_colors,
linewidths = [4*ww for ww in lw],
antialiaseds = (1,),
transOffset = ax.transData,
)
# update view
minx = amin(ravel(edge_pos[:,:,0]))
maxx = amax(ravel(edge_pos[:,:,0]))
miny = amin(ravel(edge_pos[:,:,1]))
maxy = amax(ravel(edge_pos[:,:,1]))
w = maxx-minx
h = maxy-miny
padx, pady = 0.05*w, 0.05*h
corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
ax.update_datalim( corners)
ax.autoscale_view()
edge_collection.set_zorder(1) # edges go behind nodes
ax.add_collection(edge_collection)
if arrow_collection:
arrow_collection.set_zorder(1) # edges go behind nodes
ax.add_collection(arrow_collection)
return edge_collection
示例13: ani_frame
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
def ani_frame(pos, t1, t2):
fig, ax = plt.subplots()
fig.patch.set_facecolor('green')
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# Push axis slightly off teh edge of the screen to remove any border
ax.set_position([-0.01, -0.01, 1.02, 1.02])
ax.set_axis_bgcolor('green')
ax.xaxis.label.set_color('green')
ax.yaxis.label.set_color('green')
# Make it nice and square, the final resolution is this times the DPI
fig.set_size_inches([3,3])
east = pos['East'].squeeze()
north = pos['North'].squeeze()
time = pos['time']
# Plot the whole path as a faint color
bg_idx = np.where((time >= t1) & (time <= t2))
col = (0.2, 0.2, 0.2)
background1, = ax.plot(east[bg_idx], north[bg_idx], color=col, linewidth=3)
col = (0.8, 0.8, 0.8)
background2, = ax.plot(east[bg_idx], north[bg_idx], color=col)
# Get the samples that are in this time window
def getIdx(t):
idx = np.where((time > (t - lag)) & (time <= t))
return idx
# Create the plot of the recent data
idx = getIdx(t1)
col = (0.1, 0.1, 0.8)
x = east[idx]
y = north[idx]
t = (t1 - time[idx]) / lag
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, array=t, cmap=plt.get_cmap('copper'), norm=plt.Normalize(0,1), lw=2)
lc.set_array(t)
lc.set_linewidth(3)
lc.set_zorder(20) # make sure trail is on top
ax.add_collection(lc)
# Mask out the path
def init():
lc.set_segments([])
lc.set_array([])
lc.set_linewidth(0)
return lc,
# Plot a segment of the path
def update_img(t):
idx = getIdx(t)
x = east[idx]
y = north[idx]
col = (double) (t - time[idx]) / lag
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc.set_segments(segments)
lc.set_array(col)
lc.set_linewidth(3)
ax.add_collection(lc)
ax.autoscale()
plt.draw()
return lc,
ani = animation.FuncAnimation(fig,update_img,np.arange(t1,t2,step=1000/fps),interval=0,blit=False)
writer = animation.writers['ffmpeg'](fps=30)
ani.save('demo.mp4',dpi=dpi,fps=30,writer=writer)
return lc
示例14: plot
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
#.........这里部分代码省略.........
"in the second MultiIndex level of bus_sizes"
bus_sizes = bus_sizes.sort_index(level=0, sort_remaining=False)
patches = []
for b_i in bus_sizes.index.levels[0]:
s = bus_sizes.loc[b_i]
radius = s.sum()**0.5
ratios = s/s.sum()
start = 0.25
for i, ratio in ratios.iteritems():
patches.append(Wedge((x.at[b_i], y.at[b_i]), radius,
360*start, 360*(start+ratio),
facecolor=bus_colors[i]))
start += ratio
bus_collection = PatchCollection(patches, match_original=True)
ax.add_collection(bus_collection)
else:
c = pd.Series(bus_colors, index=network.buses.index)
if c.dtype == np.dtype('O'):
c.fillna("b", inplace=True)
c = list(c.values)
s = pd.Series(bus_sizes, index=network.buses.index, dtype="float").fillna(10)
bus_collection = ax.scatter(x, y, c=c, s=s, cmap=bus_cmap)
def as_branch_series(ser):
if isinstance(ser, dict) and set(ser).issubset(branch_components):
return pd.Series(ser)
elif isinstance(ser, pd.Series):
if isinstance(ser.index, pd.MultiIndex):
return ser
index = ser.index
ser = ser.values
else:
index = network.lines.index
return pd.Series(ser,
index=pd.MultiIndex(levels=(["Line"], index),
labels=(np.zeros(len(index)),
np.arange(len(index)))))
line_colors = as_branch_series(line_colors)
line_widths = as_branch_series(line_widths)
if not isinstance(line_cmap, dict):
line_cmap = {'Line': line_cmap}
branch_collections = []
for c in network.iterate_components(branch_components):
l_defaults = defaults_for_branches[c.name]
l_widths = line_widths.get(c.name, l_defaults['width'])
l_nums = None
l_colors = line_colors.get(c.name, l_defaults['color'])
if isinstance(l_colors, pd.Series):
if issubclass(l_colors.dtype.type, np.number):
l_nums = l_colors
l_colors = None
else:
l_colors.fillna(l_defaults['color'], inplace=True)
if not geometry:
segments = (np.asarray(((c.df.bus0.map(x),
c.df.bus0.map(y)),
(c.df.bus1.map(x),
c.df.bus1.map(y))))
.transpose(2, 0, 1))
else:
from shapely.wkt import loads
from shapely.geometry import LineString
linestrings = c.df.geometry.map(loads)
assert all(isinstance(ls, LineString) for ls in linestrings), \
"The WKT-encoded geometry in the 'geometry' column must be composed of LineStrings"
segments = np.asarray(list(linestrings.map(np.asarray)))
if basemap and basemap_present:
segments = np.transpose(bmap(*np.transpose(segments, (2, 0, 1))), (1, 2, 0))
l_collection = LineCollection(segments,
linewidths=l_widths,
antialiaseds=(1,),
colors=l_colors,
transOffset=ax.transData)
if l_nums is not None:
l_collection.set_array(np.asarray(l_nums))
l_collection.set_cmap(line_cmap.get(c.name, None))
l_collection.autoscale()
ax.add_collection(l_collection)
l_collection.set_zorder(1)
branch_collections.append(l_collection)
bus_collection.set_zorder(2)
ax.update_datalim(compute_bbox_with_margins(margin, x, y))
ax.autoscale_view()
ax.set_title(title)
return (bus_collection,) + tuple(branch_collections)
示例15: LineCollection
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_zorder [as 别名]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.invert_yaxis()
ax.axis('equal')
for obs in obstacles:
ax.add_patch(plt.Polygon(obs, fc='#404040'))
ax.add_patch(plt.Circle(target_pos, target_rad, ec='None', fc='red'))
# Draw graph
edges = LineCollection(([dataset[v1][:2], dataset[v2][:2]] for v1, v2 in graph.get_edgelist()))
edges.set_color('Lavender')
edges.set_zorder(1)
ax.add_collection(edges)
# Draw points
params = {}
if args.clustering:
# Open the vertex dendogram
print 'Loading clustering...'
membership = cPickle.load(open(args.clustering, 'rb'))
params['c'] = membership
params['cmap'] = plt.get_cmap('hsv')
# Highlight boundary points
boundary = [v.index for v in graph.vs
if sum((membership[nid] != membership[v.index]
for nid in graph.neighbors(v.index))) > 7]