本文整理汇总了Python中matplotlib.collections.LineCollection.set_color方法的典型用法代码示例。如果您正苦于以下问题:Python LineCollection.set_color方法的具体用法?Python LineCollection.set_color怎么用?Python LineCollection.set_color使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.collections.LineCollection
的用法示例。
在下文中一共展示了LineCollection.set_color方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plotcf
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def plotcf(grid, phase, modulus, darken=None, axes=None, linestylep="solid", linewidthp=1, color="k", **kwargs):
r"""Plot the modulus of a complex valued function
:math:`f:\mathbb{R} \rightarrow \mathbb{C}`
together with its phase in a color coded fashion.
:param grid: The grid nodes of the real domain R
:param phase: The phase of the complex domain result f(grid)
:param modulus: The modulus of the complex domain result f(grid)
:param darken: Whether to take into account the modulus of the data to darken colors.
:param axes: The axes instance used for plotting.
:param linestylep: The line style of the phase curve.
:param linewidthp: The line width of the phase curve.
:param color: The color of the phase curve.
"""
# Color mapping
rgb_colors = color_map(modulus, phase=phase, modulus=modulus, darken=darken)
# Put all the vertical line into a collection
segments = [array([[node, 0], [node, value]]) for node, value in zip(grid, modulus)]
line_segments = LineCollection(segments)
# Set some properties of the lines
rgb_colors = line_segments.to_rgba(rgb_colors)
line_segments.set_color(rgb_colors[0])
line_segments.set_linestyle(linestylep)
line_segments.set_linewidth(linewidthp)
# Plot to the given axis instance or retrieve the current one
if axes is None:
axes = gca()
# Plot the phase
axes.add_collection(line_segments)
# Plot the modulus
axes.plot(grid, modulus, color=color, **kwargs)
示例2: changeVecteur
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def changeVecteur(self, ech=1.0, col=None):
""" modifie les valeurs de vecteurs existants"""
self.drawVecteur(False)
if type(ech) == type((3, 4)):
if len(ech) >= 1:
ech = ech[0]
# previous object
obj = self.getObjFromType("vecteur")
if obj == None:
return
# change coordinates
dep, arr_old, ech_old = obj.getData()
arr = dep + (arr_old - dep) * ech / ech_old
# new object
lc1 = LineCollection(zip(dep, arr))
lc1.set_transform(self.transform)
if col == None:
col = wx.Color(0, 0, 255)
a = col.Get()
col = (a[0] / 255, a[1] / 255, a[2] / 255)
lc1.set_color(col)
obj = GraphicObject("vecteur", lc1, False, None)
obj.setData([dep, arr, ech])
self.addGraphicObject(obj)
self.cnv.collections[0] = lc1
self.redraw()
示例3: segments
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def segments(X,Y,color=(1,0,0,0)):
N = X.shape[0]
z = np.zeros((N,2,2));
z[:,0,:] = X
z[:,1,:] = Y
lc = LineCollection(z)
lc.set_color(color)
plt.gca().add_collection(lc)
示例4: plotgraph
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def plotgraph(xy,edges,edgecolor='b'):
lcol = xy[edges]
lc = LineCollection(xy[edges])
lc.set_linewidth(0.1)
lc.set_color(edgecolor)
pl.gca().add_collection(lc)
#pl.plot(xy[:,0], xy[:,1], 'ro')
pl.xlim(xy[:,0].min(), xy[:,0].max())
pl.ylim(xy[:,1].min(), xy[:,1].max())
pl.show()
示例5: plot
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def plot(self, show_minima=False, linewidth=0.5, axes=None):
"""draw the disconnectivity graph using matplotlib
don't forget to call calculate() first
also, you must call pyplot.show() to actually see the plot
"""
import matplotlib as mpl
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
self.line_segments = self._get_line_segments(self.tree_graph, eoffset=self.eoffset)
#set up how the figure should look
if axes is not None:
ax = axes
else:
fig = plt.figure(figsize=(6,7))
fig.set_facecolor('white')
ax = fig.add_subplot(111, adjustable='box')
ax.tick_params(axis='y', direction='out')
ax.yaxis.tick_left()
ax.spines['left'].set_color('black')
ax.spines['left'].set_linewidth(0.5)
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['right'].set_color('none')
# plt.box(on=True)
#draw the minima as points
if show_minima:
leaves = self.tree_graph.get_leaves()
energies = [self._getEnergy(leaf.data["minimum"]) for leaf in leaves]
xpos = [leaf.data["x"] for leaf in leaves]
ax.plot(xpos, energies, 'o')
# draw the line segments
# use LineCollection because it's much faster than drawing the lines individually
linecollection = LineCollection([ [(x[0],y[0]), (x[1],y[1])] for x,y in self.line_segments])
linecollection.set_linewidth(linewidth)
linecollection.set_color("k")
ax.add_collection(linecollection)
# scale the axes appropriately
ax.relim()
ax.autoscale_view(scalex=True, scaley=True, tight=None)
#remove xtics
ax.set_xticks([])
示例6: segments
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def segments(self, points, color='black', **kwargs):
'plot line'
segments = numpy.concatenate([numpy.array([xy[:-1], xy[1:]]).swapaxes(0,1) for xy in points], axis=0)
from matplotlib.collections import LineCollection
lc = LineCollection(segments, **kwargs)
ax = self.gca()
ax.add_collection(lc)
if isinstance(color, str):
lc.set_color(color)
else:
array = numpy.concatenate([.5 * (v[:-1] + v[1:]) for v in color], axis=0)
lc.set_array(array)
self.sci(lc)
return lc
示例7: plot
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def plot(self, plot, col):
# Set the scale of the plot
if self.log_x:
plot.xscale('log')
if self.log_y:
plot.yscale('log')
# Process the values
values = []
for x in self.get_x_data_gen().get_values():
for y in self.get_y_data_gen().get_values():
values.append(zip(x,y))
lines = LineCollection(values)
lines.set_color(col)
lines.set_label(str(self.get_name()))
# Plot the values
plot.add_collection(lines)
示例8: plot_trajectory_ellipse
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [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
示例9: plotExpectationContours
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def plotExpectationContours(self, projection = [0,0], showDU=False, showMU=False, plot=None, alpha=1):
if plot is None:
plot = pl.figure().add_subplot(1,1,1)
self.setLimits(xprojection=projection)
self.labelAxes(plot)
mpl.rcParams['lines.linewidth']=1
minx = min(self.OD.indAttr())-projection[0]
maxx = max(self.OD.indAttr())+projection[1]
x = np.array([np.linspace(minx, maxx, self.xres)]).T
y_pred = self.ED.getExpectationsAt(x,False)
DUvals=np.zeros(len(x))
MUvals=np.zeros(len(x))
if showDU:
DUvals = self.OD.distanceUncertainty(x)
if showMU:
MUvals = self.ED.misclassUncertainty(x)
scaling = 1-np.minimum(np.ones(len(x)),DUvals+MUvals)
maxLW = 3
minLW = 0.25
for i,b in enumerate(self.OD.bins):
alpha=1
#alpha = 1-(abs(i-len(self.OD.bins)/2.0)/float(len(self.OD.bins)/2.0)) # Weight the colour of the contour to the distance from the median
points = np.array([x[:,0], y_pred[b]]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# create a (r,g,b,a) color description for each line segment
cmap = []
for a in segments:
# the x-value for this segment is:
x0 = a.mean(0)[0]
# so it has a scaling value of:
s0 = np.interp(x0,x[:,0],scaling)
cmap.append([1-s0,0,s0,alpha])
# Create the line collection object, and set the color parameters.
distFromMedian = 2 * abs(b - 0.5)
lw = (1 - distFromMedian) * (maxLW-minLW)+minLW
#if b== 0.5:
# lw = 3
lc = LineCollection(segments, linewidths=lw)
lc.set_color(cmap)
plot.add_collection(lc)
return plot
示例10: stemcf
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def stemcf(grid, phase, modulus, darken=False, axes=None, linestylep="solid", linewidthp=2, color=None, markerp="o", **kwargs):
r"""
Stemplot the modulus of a complex valued function :math:`f:I \rightarrow C` together with its phase in a color coded fashion.
:param grid: The grid nodes of the real domain R
:param phase: The phase of the complex domain result f(grid)
:param modulus: The modulus of the complex domain result f(grid)
:param darken: Whether to take into account the modulus of the data to darken colors.
:param axes: The axes instance used for plotting.
:param linestylep: The line style of the phase curve.
:param linewidthp: The line width of the phase curve.
:param color: The color of the stemmed markers.
:param markerp: The shape of the stemmed markers.
.. note:: Additional keyword arguments are passe to the plot function.
"""
# Color mapping
rgb_colors = color_map(grid, phase=phase, modulus=modulus, darken=darken)
# Put all the vertical line into a collection
segments = [ array([[node,0], [node,value]]) for node, value in zip(grid, modulus) ]
line_segments = LineCollection(segments)
# Set some properties of the lines
rgb_colors = line_segments.to_rgba(rgb_colors)
line_segments.set_color(rgb_colors[0])
line_segments.set_linestyle(linestylep)
line_segments.set_linewidth(linewidthp)
# Plot to the given axis instance or retrieve the current one
if axes is None:
axes = gca()
# Plot the phase
axes.add_collection(line_segments)
# Plot the modulus
if color is None:
# Scatter has a problem with complex data type, make sure values are purely real
axes.scatter(grid, real(modulus), c=rgb_colors[0], **kwargs)
else:
axes.plot(grid, modulus, linestyle="", marker=markerp, color=color, **kwargs)
# Plot the ground line
axes.plot(grid, zeros(grid.shape), linestyle=linestylep, color="k", **kwargs)
示例11: plot_fracdos
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def plot_fracdos():
K1=1.4
K2=1.0
nsite=100
target_block=(0,0)
dmu_mag=0.01
fnames=['fracdos_W1%s_W2%s_U%s_N%s_dmu%s_%s.dat'%(K1,K2,0.,nsite,dmu,target_block) for dmu in [dmu_mag,-dmu_mag]]
pls=[loadtxt(fname) for fname in fnames]
pls=array(pls)-0.5
nsite=pls.shape[-1]
pls_left=pls[...,:nsite/2]
pls_right=pls[...,nsite/2:]
print 'occupation in left block -> %s, right block -> %s.'%(sum(pls_left,axis=(-1,-2)),sum(pls_right,axis=(-1,-2)))
ion()
fig=figure(figsize=(7,5))
lw=2
lc='r'
axs=[]
site_loc=append(arange(20),arange(25,45))
sites=append(arange(20),arange(nsite-20,nsite))
for n in xrange(len(pls)):
pln=pls[n].sum(axis=0)
ax=subplot(11+n+100*len(pls),sharex=axs[0] if n==1 else None)
text(0.02,0.9,'(a)' if n==0 else '(b)',transform=ax.transAxes)
color='k'
lc=LineCollection([[(posi,0),(posi,pln[sitei].item())] for posi,sitei in zip(site_loc,sites)])
lc.set_linewidth(lw)
lc.set_color(color)
#lc.set_linestyle('--' if s==1 else '-')
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
ylabel(r'$\rho-\bar{\rho}$',fontsize=LABELSIZE)
ax.set_xticks(list(site_loc[:20:5])+[23]+list(site_loc[19::5]))
ax.set_xticklabels(list(sites[:20:5]+1)+[r'$\bf{\ldots}$']+list(sites[19::5]))
yticks([-0.5,-0.25,0,0.25,0.5])
xlabel(r'$N$',fontsize=LABELSIZE)
subplots_adjust(hspace=0.05)
pdb.set_trace()
savefig('fracdos.eps')
savefig('fracdos.png')
示例12: plot_sparse_trajectory
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [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
示例13: show_mf_wave
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
def show_mf_wave(**kwargs):
K1=1.4
K2=1.0
U=0.0
nsite=100
dmu=0.01
lw=2
lc='r'
mjfile='mf_W1%s_W2%s_U%s_N%s_dmu%s.npy'%(K1,K2,U,nsite,dmu)
pls=load(mjfile)
ampl=(pls[:2]*pls[:2].conj()).real
nsite=pls.shape[1]
ion()
fig=figure(figsize=(7,4))
for n in xrange(2):
pln=ampl[n]
ax=subplot(121+n)
lc=LineCollection([[(i+1,0),(i+1,pln[i].item())] for i in xrange(nsite)])
lc.set_linewidth(lw)
lc.set_color('k')
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
if n==0:
text(0.02,0.9,'(a)',transform=ax.transAxes,color='k')
xlim(0,22)
xticks(arange(1,22,5))
ylabel(r'$|\phi_j|^2$',fontsize=LABELSIZE)
else:
text(0.02,0.9,'(b)',transform=ax.transAxes,color='k')
xlim(79,101)
yticks([])
ylim(0,0.2)
xlabel('$j$',fontsize=LABELSIZE)
tight_layout(w_pad=0.5)
pdb.set_trace()
savefig('mf.eps')
savefig('mf.png')
示例14: ScatterLayerArtist
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
#.........这里部分代码省略.........
headwidth=hw, headlength=hl,
scale_units='width',
scale=10 / self.state.vector_scaling)
self.mpl_artists[self.vector_index] = self.vector_artist
if self.state.xerr_visible or self.state.yerr_visible:
if self.state.xerr_visible and self.state.xerr_att is not None:
xerr = self.layer[self.state.xerr_att].ravel()
else:
xerr = None
if self.state.yerr_visible and self.state.yerr_att is not None:
yerr = self.layer[self.state.yerr_att].ravel()
else:
yerr = None
self.errorbar_artist = self.axes.errorbar(x, y, fmt='none',
xerr=xerr, yerr=yerr)
self.mpl_artists[self.errorbar_index] = self.errorbar_artist
@defer_draw
def _update_visual_attributes(self, changed, force=False):
if not self.enabled:
return
if self.state.markers_visible:
if self.state.density_map:
if self.state.cmap_mode == 'Fixed':
if force or 'color' in changed or 'cmap_mode' in changed:
self.density_artist.set_color(self.state.color)
self.density_artist.set_c(None)
self.density_artist.set_clim(self.density_auto_limits.min,
self.density_auto_limits.max)
elif force or any(prop in changed for prop in CMAP_PROPERTIES):
c = self.layer[self.state.cmap_att].ravel()
set_mpl_artist_cmap(self.density_artist, c, self.state)
if force or 'stretch' in changed:
self.density_artist.set_norm(ImageNormalize(stretch=STRETCHES[self.state.stretch]()))
if force or 'dpi' in changed:
self.density_artist.set_dpi(self._viewer_state.dpi)
if force or 'density_contrast' in changed:
self.density_auto_limits.contrast = self.state.density_contrast
self.density_artist.stale = True
else:
if self.state.cmap_mode == 'Fixed' and self.state.size_mode == 'Fixed':
if force or 'color' in changed:
self.plot_artist.set_color(self.state.color)
if force or 'size' in changed or 'size_scaling' in changed:
self.plot_artist.set_markersize(self.state.size *
self.state.size_scaling)
else:
# TEMPORARY: Matplotlib has a bug that causes set_alpha to
# change the colors back: https://github.com/matplotlib/matplotlib/issues/8953
示例15: float
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_color [as 别名]
ball_rad = float(tokens[1])
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]