本文整理汇总了Python中matplotlib.collections.LineCollection.set_alpha方法的典型用法代码示例。如果您正苦于以下问题:Python LineCollection.set_alpha方法的具体用法?Python LineCollection.set_alpha怎么用?Python LineCollection.set_alpha使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.collections.LineCollection
的用法示例。
在下文中一共展示了LineCollection.set_alpha方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def plot(ax, x, y, time, sim_type):
assert(len(x) == len(y) == len(time))
l = len(time)
if use_hf_coloration:
time_to_grayscale = 0.8 / 23.6 # for HF coloring
else:
time_to_grayscale = 0.8 / time[l-1]
colors = []
for i in range(l-1):
if use_hf_coloration:
color = get_hf_color(time[i]) # time[] is really HF
else:
g = 0.8 - (time[i] * time_to_grayscale)**2.0
if sim_type == 'driven':
color = (g, 1.0, g, 0.8)
else:
color = (g, g, 1.0, 1.0)
colors.append(color)
points = zip(x,y)
segments = zip(points[:-1], points[1:])
lc = LineCollection(segments, colors=colors)
lc.set_alpha(1.0)
lc.set_linewidth(1.0)
lc.set_antialiased(True)
ax.add_collection(lc)
if use_hf_coloration:
end_points.append((x[l-1], y[l-1], get_hf_color(time[l-1])))
else:
end_points.append((x[l-1], y[l-1], COLOR[sim_type]))
示例2: __plot_all
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def __plot_all(self):
total = len(self.data)
count = 0.0
for timeStamp in self.data:
if len(self.data[timeStamp]) < 2:
self.parent.threadPlot = None
return None, None
if self.fade:
alpha = (total - count) / total
else:
alpha = 1
data = self.data[timeStamp].items()
peakF, peakL = self.extent.get_peak_fl()
segments, levels = self.__create_segments(data)
lc = LineCollection(segments)
lc.set_array(numpy.array(levels))
lc.set_norm(self.__get_norm(self.autoL, self.extent))
lc.set_cmap(self.colourMap)
lc.set_linewidth(self.lineWidth)
lc.set_gid('plot')
lc.set_alpha(alpha)
self.axes.add_collection(lc)
count += 1
return peakF, peakL
示例3: __plot_all
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def __plot_all(self, spectrum):
total = len(spectrum)
count = 0.0
for timeStamp in spectrum:
if self.settings.fadeScans:
alpha = (total - count) / total
else:
alpha = 1
data = spectrum[timeStamp].items()
peakF, peakL = self.extent.get_peak_fl()
segments, levels = self.__create_segments(data)
if segments is not None:
lc = LineCollection(segments)
lc.set_array(numpy.array(levels))
lc.set_norm(self.__get_norm(self.settings.autoL, self.extent))
lc.set_cmap(self.colourMap)
lc.set_linewidth(self.lineWidth)
lc.set_gid('plot')
lc.set_alpha(alpha)
self.axes.add_collection(lc)
count += 1
return peakF, peakL
示例4: _plotpartial
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def _plotpartial(ax, partial, downsample=1, cmap='inferno', exp=1, linewidth=1, avg=True):
# columns: time, freq, amp, phase, bw
segments, Z = _segmentsZ(partial, downsample=downsample, exp=exp, avg=avg)
lc = LineCollection(segments, cmap=cmap)
# Set the values used for colormapping
lc.set_array(Z)
lc.set_linewidth(linewidth)
lc.set_alpha(None)
ax.add_collection(lc, autolim=True)
示例5: plot_trajectory_ellipse
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def plot_trajectory_ellipse(frame, varx="attr_VARX", vary="attr_VARY", covxy="attr_COVXY", opacity_factor=1):
"""
Draw the trajectory and uncertainty ellipses around teach point.
1) Scatter of points
2) Trajectory lines
3) Ellipses
:param frame: Trajectory
:param opacity_factor: all opacity values are multiplied by this. Useful when used to plot multiple Trajectories in
an overlay plot.
:return: axis
"""
ellipses = []
segments = []
start_point = None
for i, pnt in frame.iterrows():
# The ellipse
U, s, V = np.linalg.svd(np.array([[pnt[varx], pnt[covxy]],
[pnt[covxy], pnt[vary]]]), full_matrices=True)
w, h = s**.5
theta = np.arctan(V[1][0]/V[0][0]) # == np.arccos(-V[0][0])
ellipse = {"xy":pnt[list(frame.geo_cols)].values, "width":w, "height":h, "angle":theta}
ellipses.append(Ellipse(**ellipse))
# The line segment
x, y = pnt[list(frame.geo_cols)][:2]
if start_point:
segments.append([start_point, (x, y)])
start_point = (x, y)
ax = plt.gca()
ellipses = PatchCollection(ellipses)
ellipses.set_facecolor('none')
ellipses.set_color("green")
ellipses.set_linewidth(2)
ellipses.set_alpha(.4*opacity_factor)
ax.add_collection(ellipses)
frame.plot(kind="scatter", x=frame.geo_cols[0], y=frame.geo_cols[1], marker=".", ax=plt.gca(), alpha=opacity_factor)
lines = LineCollection(segments)
lines.set_color("gray")
lines.set_linewidth(1)
lines.set_alpha(.2*opacity_factor)
ax.add_collection(lines)
return ax
示例6: algo
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def algo (region,output, word):
reg = [0 for i in range(0,23)]
total = 0
for line in region: #reg_num number
items = line.rstrip('\n').split('\t')
reg[int(items[0])]=int(items[1])
total = total+int(items[1])
reg=np.array(reg)
max_percent=np.max(reg)
plt.figure(figsize=(15,15))
ax = plt.subplot(111)
m = Basemap(projection='merc', lat_0=45, lon_0=0,
resolution = 'h', area_thresh = 10.0,
llcrnrlat=41.33, llcrnrlon=-5,
urcrnrlat=51.5, urcrnrlon=9.7)
m.drawcoastlines()
#m.drawcountries() # french border does not fit with region ones
m.fillcontinents(color='lightgrey',lake_color='white')
m.drawmapboundary(fill_color='white')
sf = shapefile.Reader("./geodata/FRA_adm1")
shapes = sf.shapes()
records = sf.records()
for record, shape in zip(records,shapes):
lons,lats = zip(*shape.points)
data = np.array(m(lons, lats)).T
if len(shape.parts) == 1:
segs = [data,]
else:
segs = []
for i in range(1,len(shape.parts)):
index = shape.parts[i-1]
index2 = shape.parts[i]
segs.append(data[index:index2])
segs.append(data[index2:])
lines = LineCollection(segs,antialiaseds=(1,))
lines.set_edgecolors('k')
lines.set_linewidth(0.5)
lines.set_facecolors('brown')
lines.set_alpha(float(reg[record[3]])/max_percent) #record[3] est le numero de region
ax.add_collection(lines)
plt.savefig(word+'-'+str(total)+'.png',dpi=300)
return 0
示例7: plot
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def plot(self, ax=None, cmapname=None, cmap=None, linewidth=1,
edgecolor='grey', facecolor=None, alpha=1):
"""Plot the geometries on the basemap using the defined colors
Parameters:
-----------
ax : matplotlib.axis object
An axis object for plots. Overwrites the self.ax attribute.
cmapname : string
Name of the color map from matplotlib (LINK!) (default: 'seismic')
cmap : matplotlib colormap
You can create you own colormap and pass it to the plot.
linewidth : float
Width of the lines.
edgecolor : string, float or iterable
Definition of the edge color. Can be an iterable with a color
definition for each geometry, a string with one color for
all geometries or a float to define one color for all geometries
from the cmap.
facecolor : string, float or iterable
Definition of the face color. See edgecolor.
alpha : float
Level of transparency.
"""
if ax is not None:
self.ax = ax
n = 0
if facecolor is None:
facecolor = self.color
if edgecolor is None:
edgecolor = self.color
if cmapname is not None:
self.cmapname = cmapname
if self.data is not None:
self.data = np.array(self.data)
if cmap is None:
cmap = plt.get_cmap(self.cmapname)
for geo in self.geometries:
vectors = self.get_vectors_from_postgis_map(geo)
lines = LineCollection(vectors, antialiaseds=(1, ))
lines.set_facecolors(self.select_color(facecolor, cmap, n))
lines.set_edgecolors(self.select_color(edgecolor, cmap, n))
lines.set_linewidth(linewidth)
lines.set_alpha(alpha)
self.ax.add_collection(lines)
n += 1
示例8: plot_sparse_trajectory
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def plot_sparse_trajectory(trajectory, r=50, opacity_factor=1, plot_text=True,
num_col="segment_sparcify_n", min_static=100):
"""
Plots a sparsified trajectory as circles with the number of points they represent as a number inside.
:param trajectory: Trajectory object
:param r: the radius of circles
:param num_col: where to find the number to put in the circles
:param min_static: minimum count to change color of circle
:param plot_text: put the text with num of points in the circle?
:return: ax
"""
ax = plt.gca()
trajectory.plot(kind="scatter", x=trajectory.geo_cols[0], y=trajectory.geo_cols[1], marker=".",
ax=plt.gca(), alpha=0.0*opacity_factor)
circles = []
segments = []
start_point = None
for i, pnt in trajectory.iterrows():
circles.append(Circle(pnt[list(trajectory.geo_cols)].values, radius=r))
if plot_text:
plt.text(*pnt[list(trajectory.geo_cols)], s=str(int(pnt[num_col])), fontsize=12)
x, y = pnt[list(trajectory.geo_cols)][:2]
if start_point:
segments.append([start_point, (x, y)])
start_point = (x, y)
circles = PatchCollection(circles)
circles.set_facecolor(['none' if cnt < min_static else 'red' for cnt in trajectory[num_col].values])
circles.set_alpha(.5*opacity_factor)
ax.add_collection(circles)
lines = LineCollection(segments)
lines.set_color("gray")
lines.set_alpha(.2*opacity_factor)
ax.add_collection(lines)
return ax
示例9: drawcountry
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def drawcountry(self,
ax,
base_map,
iso2,
color,
alpha = 1):
if iso2 not in self.countries:
raise ValueError, "Where is that country ?"
vertices = self.countries[iso2]
shape = []
for vertex in vertices:
longs, lats = zip(*vertex)
# conversion to plot coordinates
x,y = base_map(longs, lats)
shape.append(zip(x,y))
lines = LineCollection(shape,antialiaseds=(1,))
lines.set_facecolors(cm.hot(np.array([color,])))
lines.set_edgecolors('white')
lines.set_linewidth(0.5)
lines.set_alpha(alpha)
ax.add_collection(lines)
示例10: odometry_error_bar
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def odometry_error_bar(fig_num, info, pred_mean, sampling_time='1s', color_bar='Reds'):
########################
# Plot Bar
########################
matplotlib.rcParams.update({'font.size': 15, 'font.weight': 'bold'})
fig, ax = plt.subplots()
resample_info = info.resample(resampling_time).mean()
x = resample_info.index.to_pydatetime()
x[:] = [(i-x[0]).total_seconds() for i in x]
y = info.inliers_matches_ratio_th
# Display Odometry error information
from numpy import linalg as la
y = np.ones(len(x))
sd = la.norm(pred_mean, axis=1)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib.colors import LinearSegmentedColormap as lscm
cmap = plt.get_cmap(color_bar)
norm = plt.Normalize(0.00, 0.0634491701615)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(sd)
lc.set_linewidth(100)
lc.set_alpha(0.8)
plt.gca().add_collection(lc)
ax.tick_params('y', colors='k')
ax.set_xlabel(r'Time [$s$]', fontsize=25, fontweight='bold')
ax.tick_params('x', colors='k')
ax.set_ylim([0.5, 1.5])
ax.set_xlim([x[0], x[len(x)-1]])
plt.show(block=True)
示例11: arl_dem_figure
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def arl_dem_figure(fig_num, dem_file, trajectory, pred_mean, kf_trajectory, frames_trajectory, color_bar='Reds'):
########################
# Load Terrain DEM
########################
import os
plydata = PlyData.read(open(os.path.expanduser(dem_file)))
vertex = plydata['vertex'].data
[dem_px, dem_py, dem_pz] = (vertex[t] for t in ('x', 'y', 'z'))
# define grid.
npts=100
dem_xi = np.linspace(min(dem_px), max(dem_px), npts)
dem_yi = np.linspace(min(dem_py), max(dem_py), npts)
# grid the data.
dem_zi = griddata(dem_px, dem_py, dem_pz, dem_xi, dem_yi, interp='linear')
matplotlib.rcParams.update({'font.size': 30, 'font.weight': 'bold'})
fig = plt.figure(fig_num, figsize=(28, 16), dpi=120, facecolor='w', edgecolor='k')
ax = fig.add_subplot(111)
#fig, ax = plt.subplots()
# Display the DEM
plt.rc('text', usetex=False)# activate latex text rendering
CS = plt.contour(dem_xi, dem_yi, dem_zi, 15, linewidths=0.5, colors='k')
CS = plt.contourf(dem_xi, dem_yi, dem_zi, 15, cmap=plt.cm.gray, vmax=abs(dem_zi).max(), vmin=-abs(dem_zi).max())
# plot data points.
plt.xlim(min(dem_px), max(dem_xi))
plt.ylim(min(dem_py), max(dem_yi))
# Display Ground Truth trajectory
from numpy import linalg as la
x = trajectory[1:trajectory.shape[0]-1,0]
y = trajectory[1:trajectory.shape[0]-1,1]
sd = la.norm(pred_mean, axis=1)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib.colors import LinearSegmentedColormap as lscm
cmap = plt.get_cmap(color_bar)
norm = plt.Normalize(0.00, 0.0634491701615)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(sd)
lc.set_linewidth(40)
lc.set_alpha(0.8)
plt.gca().add_collection(lc)
#color bar of the covarianve
#h_cbar = plt.colorbar(lc)#, orientation='horizontal')
#h_cbar.ax.set_ylabel(r' odometry error[$m/s$]', fontsize=25, fontweight='bold')
# Color bar of the dem
#cbar = plt.colorbar() # draw colorbar
#cbar.ax.set_ylabel(r' terrain elevation[$m$]', fontsize=25, fontweight='bold')
# Plot all the image frames line
fr_x = frames_trajectory[:,0]
fr_y = frames_trajectory[:,1]
ax.plot(fr_x, fr_y,
#marker='s',
linestyle='-', lw=2, alpha=0.5, color=[0.0, 0.3, 1.0],
label='slam trajectory',
zorder=98)
# Plot all the image frames
ax.scatter(fr_x, fr_y, marker='s', facecolor=[0.0,0.3,1.0], edgecolor='b',
label='image frames', s=300, alpha=0.2, zorder=99)
# Plot the key frames
kf_x = kf_trajectory[:,0]
kf_y = kf_trajectory[:,1]
ax.scatter(kf_x, kf_y, marker='D', facecolor=[0.2,1.0,0.0], edgecolor='b',
label='keyframes', s=250, alpha=0.8, zorder=100)
import os
from matplotlib.cbook import get_sample_data
from matplotlib._png import read_png
import matplotlib.image as image
from scipy import ndimage
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
fn = get_sample_data(os.getcwd()+"/data/img/exoter.png", asfileobj=False)
exoter = image.imread(fn)
exoter = ndimage.rotate(exoter, 100)
imexoter = OffsetImage(exoter, zoom=0.5)
ab = AnnotationBbox(imexoter, xy=(x[0], y[0]),
xybox=None,
xycoords='data',
boxcoords="offset points",
#.........这里部分代码省略.........
示例12: plotter
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
def plotter(choice, numNeurons, numTimeSteps, maxNeurons, maxTimeSteps, reverse, numInputNeurons, colorNeurons, redStart, redEnd, greenStart, greenEnd, blueStart, blueEnd, eatNeuron, mateNeuron, fightNeuron, moveNeuron, yawNeuron, label, behaviorLabels, inputLabels):
rhythm_file = open_file(choice, "r")
line = next_line(rhythm_file)
line = next_line(rhythm_file)
figwidth = 12.0
figheight = 8.0
fig = pylab.figure(figsize=(figwidth,figheight))
ax = fig.add_subplot(111)
ax.set_xlim(0.5, maxTimeSteps+0.5)
ax.set_ylim(maxNeurons-0.5, -0.5)
pylab.title(label)
pylab.ylabel('Neuron Index')
pylab.xlabel('Time Step')
linewidth = 0.715 * fig.get_figwidth() * fig.get_dpi() / maxTimeSteps
for time in range(numTimeSteps):
x = []
y = []
colors = []
for neuron in range(numNeurons):
activ = line.split()
x.append(time+1)
y.append(neuron-0.5)
activation = float(activ[1])
if reverse:
activation = 1.0 - activation
if colorNeurons:
if neuron in range(redStart, redEnd+1):
colors.append((activation, activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, 1.0))
elif neuron in range(greenStart, greenEnd+1):
colors.append((activation*ALT_COLOR_MAX, activation, activation*ALT_COLOR_MAX, 1.0))
elif neuron in range(blueStart, blueEnd+1):
colors.append((activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, activation, 1.0))
elif neuron == eatNeuron:
colors.append((activation*ALT_COLOR_MAX, activation, activation*ALT_COLOR_MAX, 1.0))
elif neuron == mateNeuron:
colors.append((activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, activation, 1.0))
elif neuron == fightNeuron:
colors.append((activation, activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, 1.0))
elif neuron == yawNeuron:
colors.append((activation, activation, activation*ALT_COLOR_MAX, 1.0))
else:
colors.append((activation, activation, activation, 1.0))
else:
colors.append((activation, activation, activation, 1.0))
line = next_line(rhythm_file)
x.append(time+1)
y.append(neuron+0.5)
colors.append((activation, activation, activation, 1.0))
points = zip(x, y)
segments = zip(points[:-1], points[1:])
lc = LineCollection(segments, colors=colors)
lc.set_alpha(1.0)
lc.set_linewidth(linewidth)
lc.set_antialiased(False)
ax.add_collection(lc)
rhythm_file.close()
if behaviorLabels:
matplotlib.pyplot.text(maxTimeSteps+1.5, eatNeuron, "Eat", weight="ultralight", size="small", va="center")
matplotlib.pyplot.text(maxTimeSteps+1.5, mateNeuron, "Mate", weight="ultralight", size="small", va="center")
matplotlib.pyplot.text(maxTimeSteps+1.5, fightNeuron, "Fight", weight="ultralight", size="small", va="center")
matplotlib.pyplot.text(maxTimeSteps+1.5, moveNeuron, "Move", weight="ultralight", size="small", va="center")
matplotlib.pyplot.text(maxTimeSteps+1.5, yawNeuron, "Turn", weight="ultralight", size="small", va="center")
matplotlib.pyplot.text(maxTimeSteps+1.5, yawNeuron+1, "Light", weight="ultralight", size="small", va="center")
matplotlib.pyplot.text(maxTimeSteps+1.5, yawNeuron+2, "Focus", weight="ultralight", size="small", va="center")
if inputLabels:
matplotlib.pyplot.text(maxTimeSteps+1.5, 0, "Random", weight="ultralight", size="small", va="center")
matplotlib.pyplot.text(maxTimeSteps+1.5, 1, "Health", weight="ultralight", size="small", va="center")
for neuron in range(redStart, redEnd+1):
matplotlib.pyplot.text(maxTimeSteps+1.5, neuron, "R", weight="ultralight", size="small", va="center")
for neuron in range(greenStart, greenEnd+1):
matplotlib.pyplot.text(maxTimeSteps+1.5, neuron, "G", weight="ultralight", size="small", va="center")
for neuron in range(blueStart, blueEnd+1):
matplotlib.pyplot.text(maxTimeSteps+1.5, neuron, "B", weight="ultralight", size="small", va="center")
示例13: draw_networkx_edges
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
#.........这里部分代码省略.........
# 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:
x1, y1 = src
x2, y2 = dst
dx = x2-x1 # x offset
dy = y2-y1 # y offset
d = numpy.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
示例14: range
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
dbf = dbflib.open('../states/statesp020')
for npoly in range(shp.info()[0]):
# draw colored polygons on the map
shpseqs = []
shp_object = shp.read_object(npoly)
verts = shp_object.vertices()
rings = len(verts)
for ring in range(rings):
lons, lats = zip(*verts[ring])
x, y = m(lons,lats)
shpsegs.append(zip(x,y))
if ring == 0:
shapedict = dbf.read_record(npoly)
name = shapedict['STATE']
lines = LineCollection(shpsegs,antialiased=(1,))
# state_to_code dict, e.g. 'ALASKA' -> 'AK', omitted
try:
per = obama[state_to_code[name.upper()]]
except KeyError:
continue
lines.set_facecolors('k')
lines.set_alpha(0.75 * per) # shrink the percentage a bit
lines.set_edgecolors('k')
lines.set_linewidth(0.3)
ax.add_collection(lines)
plt.show()
示例15: draw_networkx_edges
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_alpha [as 别名]
#.........这里部分代码省略.........
edge_colors = tuple([colorConverter.to_rgba(c,alpha)
for c in edge_color])
elif np.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 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