本文整理匯總了Python中matplotlib.collections.LineCollection方法的典型用法代碼示例。如果您正苦於以下問題:Python collections.LineCollection方法的具體用法?Python collections.LineCollection怎麽用?Python collections.LineCollection使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.collections
的用法示例。
在下文中一共展示了collections.LineCollection方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_cap_and_joinstyle_image
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def test_cap_and_joinstyle_image():
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim([-0.5, 1.5])
ax.set_ylim([-0.5, 2.5])
x = np.array([0.0, 1.0, 0.5])
ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]])
segs = np.zeros((3, 3, 2))
segs[:, :, 0] = x
segs[:, :, 1] = ys
line_segments = LineCollection(segs, linewidth=[10, 15, 20])
line_segments.set_capstyle("round")
line_segments.set_joinstyle("miter")
ax.add_collection(line_segments)
ax.set_title('Line collection with customized caps and joinstyle')
示例2: add_ticks
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def add_ticks(da, locations, direction):
segments = [None] * (len(locations)*2)
if direction == 'vertical':
x1, x2, x3, x4 = np.array([0.0, 1/5, 4/5, 1.0]) * da.width
for i, y in enumerate(locations):
segments[i*2:i*2+2] = [((x1, y), (x2, y)),
((x3, y), (x4, y))]
else:
y1, y2, y3, y4 = np.array([0.0, 1/5, 4/5, 1.0]) * da.height
for i, x in enumerate(locations):
segments[i*2:i*2+2] = [((x, y1), (x, y2)),
((x, y3), (x, y4))]
coll = mcoll.LineCollection(segments,
color='#CCCCCC',
linewidth=1,
antialiased=False)
da.add_artist(coll)
示例3: edge_plot
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def edge_plot(ts, filename):
n = ts.num_samples
pallete = sns.color_palette("husl", 2 ** n - 1)
lines = []
colours = []
for tree in ts.trees():
left, right = tree.interval
for u in tree.nodes():
children = tree.children(u)
# Don't bother plotting unary nodes, which will all have the same
# samples under them as their next non-unary descendant
if len(children) > 1:
for c in children:
lines.append([(left, c), (right, c)])
colours.append(pallete[unrank(tree.samples(c), n)])
lc = mc.LineCollection(lines, linewidths=2, colors=colours)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
save_figure(filename)
示例4: add_lines
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def add_lines(self, levels, colors, linewidths):
'''
Draw lines on the colorbar. It deletes preexisting lines.
'''
del self.lines
N = len(levels)
x = np.array([1.0, 2.0])
X, Y = np.meshgrid(x,levels)
if self.orientation == 'vertical':
xy = [zip(X[i], Y[i]) for i in range(N)]
else:
xy = [zip(Y[i], X[i]) for i in range(N)]
col = collections.LineCollection(xy, linewidths=linewidths,
)
self.lines = col
col.set_color(colors)
self.ax.add_collection(col)
示例5: test_linecollection_scaled_dashes
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def test_linecollection_scaled_dashes():
lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
lines3 = [[[0.6, .2], [.8, .4]], [[.5, .7], [.1, .1]]]
lc1 = mcollections.LineCollection(lines1, linestyles="--", lw=3)
lc2 = mcollections.LineCollection(lines2, linestyles="-.")
lc3 = mcollections.LineCollection(lines3, linestyles=":", lw=.5)
fig, ax = plt.subplots()
ax.add_collection(lc1)
ax.add_collection(lc2)
ax.add_collection(lc3)
leg = ax.legend([lc1, lc2, lc3], ["line1", "line2", 'line 3'])
h1, h2, h3 = leg.legendHandles
for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)):
assert oh.get_linestyles()[0][1] == lh._dashSeq
assert oh.get_linestyles()[0][0] == lh._dashOffset
示例6: plot_ori
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def plot_ori(self, c):
from matplotlib import collections as mc
import matplotlib.pyplot as plt
line_len = 1
lines = [[(p[0], p[1]), (p[0] + line_len * self._angles[p][0],
p[1] + line_len * self._angles[p][1])] for p in self._nodes]
lc = mc.LineCollection(lines, linewidth=2, color='green')
_, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
xs = [p[0] for p in self._nodes]
ys = [p[1] for p in self._nodes]
plt.scatter(xs, ys, color=c)
示例7: grid
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def grid(ax):
segments,colors,linewidths = [], [], []
for x in ax.xaxis.get_minorticklocs():
segments.append([(x,ymin), (x,ymax)])
colors.append("0.75")
linewidths.append(0.50)
for x in ax.xaxis.get_majorticklocs():
segments.append([(x,ymin), (x,ymax)])
colors.append("0.50")
linewidths.append(0.75)
for y in ax.yaxis.get_minorticklocs():
segments.append([(xmin,y), (xmax,y)])
colors.append("0.75")
linewidths.append(0.50)
for y in ax.yaxis.get_majorticklocs():
segments.append([(xmin,y), (xmax,y)])
colors.append("0.50")
linewidths.append(0.75)
collection = LineCollection(segments, zorder=-10,
colors=colors, linewidths=linewidths)
ax.add_collection(collection)
示例8: colored_line_collection
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def colored_line_collection(xyz, colors, plot_mode=PlotMode.xy,
linestyles="solid", step=1, alpha=1.):
if len(xyz) / step != len(colors):
raise PlotException(
"color values don't have correct length: %d vs. %d" %
(len(xyz) / step, len(colors)))
x_idx, y_idx, z_idx = plot_mode_to_idx(plot_mode)
xs = [[x_1, x_2]
for x_1, x_2 in zip(xyz[:-1:step, x_idx], xyz[1::step, x_idx])]
ys = [[x_1, x_2]
for x_1, x_2 in zip(xyz[:-1:step, y_idx], xyz[1::step, y_idx])]
if plot_mode == PlotMode.xyz:
zs = [[x_1, x_2]
for x_1, x_2 in zip(xyz[:-1:step, z_idx], xyz[1::step, z_idx])]
segs = [list(zip(x, y, z)) for x, y, z in zip(xs, ys, zs)]
line_collection = art3d.Line3DCollection(segs, colors=colors,
alpha=alpha,
linestyles=linestyles)
else:
segs = [list(zip(x, y)) for x, y in zip(xs, ys)]
line_collection = LineCollection(segs, colors=colors, alpha=alpha,
linestyle=linestyles)
return line_collection
示例9: init_artists
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def init_artists(self, ax, plot_args, plot_kwargs):
artists = {}
if 'arcs' in plot_args:
color_opts = ['c', 'cmap', 'vmin', 'vmax', 'norm']
groups = [g for g in self._style_groups if g != 'arc']
edge_opts = filter_styles(plot_kwargs, 'arc', groups, color_opts)
paths = plot_args['arcs']
edges = LineCollection(paths, **edge_opts)
ax.add_collection(edges)
artists['arcs'] = edges
artists.update(super(ChordPlot, self).init_artists(ax, plot_args, plot_kwargs))
if 'text' in plot_args:
fontsize = plot_kwargs.get('text_font_size', 8)
labels = []
for (x, y, l, a) in zip(*plot_args['text']):
label = ax.annotate(l, xy=(x, y), xycoords='data', rotation=a,
horizontalalignment='left', fontsize=fontsize,
verticalalignment='center', rotation_mode='anchor')
labels.append(label)
artists['labels'] = labels
return artists
示例10: add_lines
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def add_lines(ax, lines, **kwargs):
"""Add lines (points in the form Nx2) to axes
Add lines (points in the form Nx2) to existing axes ax
using :class:`matplotlib:matplotlib.collections.LineCollection`.
Parameters
----------
ax : :class:`matplotlib:matplotlib.axes.Axes`
lines : :class:`numpy:numpy.ndarray`
nested Nx2 array(s)
kwargs : :class:`matplotlib:matplotlib.collections.LineCollection`
Examples
--------
See :ref:`/notebooks/visualisation/wradlib_overlay.ipynb`.
"""
try:
ax.add_collection(LineCollection([lines], **kwargs))
except AssertionError:
ax.add_collection(LineCollection([lines[None, ...]], **kwargs))
except ValueError:
for line in lines:
add_lines(ax, line, **kwargs)
示例11: show_isotonic_regression_segments
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def show_isotonic_regression_segments(X, Y, Yi, segments):
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(Y)))
lc.set_linewidths(0.5 * np.ones(nb_samples))
fig, ax = plt.subplots(1, 1, figsize=(30, 25))
ax.plot(X, Y, 'b.', markersize=8)
ax.plot(X, Yi, 'g.-', markersize=8)
ax.grid()
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
開發者ID:PacktPublishing,項目名稱:Fundamentals-of-Machine-Learning-with-scikit-learn,代碼行數:16,代碼來源:6isotonic_regression.py
示例12: convex_hull_plot_2d
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def convex_hull_plot_2d(hull, ax=None):
"""
Plot the given convex hull diagram in 2-D
Parameters
----------
hull : scipy.spatial.ConvexHull instance
Convex hull to plot
ax : matplotlib.axes.Axes instance, optional
Axes to plot on
Returns
-------
fig : matplotlib.figure.Figure instance
Figure for the plot
See Also
--------
ConvexHull
Notes
-----
Requires Matplotlib.
"""
from matplotlib.collections import LineCollection
if hull.points.shape[1] != 2:
raise ValueError("Convex hull is not 2-D")
ax.plot(hull.points[:,0], hull.points[:,1], 'o')
line_segments = [hull.points[simplex] for simplex in hull.simplices]
ax.add_collection(LineCollection(line_segments,
colors='k',
linestyle='solid'))
_adjust_bounds(ax, hull.points)
return ax.figure
示例13: _add_solids
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def _add_solids(self, X, Y, C):
'''
Draw the colors using :meth:`~matplotlib.axes.Axes.pcolormesh`;
optionally add separators.
'''
if self.orientation == 'vertical':
args = (X, Y, C)
else:
args = (np.transpose(Y), np.transpose(X), np.transpose(C))
kw = dict(cmap=self.cmap,
norm=self.norm,
alpha=self.alpha,
edgecolors='None')
# Save, set, and restore hold state to keep pcolor from
# clearing the axes. Ordinarily this will not be needed,
# since the axes object should already have hold set.
_hold = self.ax.ishold()
self.ax.hold(True)
col = self.ax.pcolormesh(*args, **kw)
self.ax.hold(_hold)
#self.add_observer(col) # We should observe, not be observed...
if self.solids is not None:
self.solids.remove()
self.solids = col
if self.dividers is not None:
self.dividers.remove()
self.dividers = None
if self.drawedges:
linewidths = (0.5 * mpl.rcParams['axes.linewidth'],)
self.dividers = collections.LineCollection(self._edges(X, Y),
colors=(mpl.rcParams['axes.edgecolor'],),
linewidths=linewidths)
self.ax.add_collection(self.dividers)
示例14: add_lines
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def add_lines(self, levels, colors, linewidths, erase=True):
'''
Draw lines on the colorbar.
*colors* and *linewidths* must be scalars or
sequences the same length as *levels*.
Set *erase* to False to add lines without first
removing any previously added lines.
'''
y = self._locate(levels)
igood = (y < 1.001) & (y > -0.001)
y = y[igood]
if cbook.iterable(colors):
colors = np.asarray(colors)[igood]
if cbook.iterable(linewidths):
linewidths = np.asarray(linewidths)[igood]
N = len(y)
x = np.array([0.0, 1.0])
X, Y = np.meshgrid(x, y)
if self.orientation == 'vertical':
xy = [zip(X[i], Y[i]) for i in xrange(N)]
else:
xy = [zip(Y[i], X[i]) for i in xrange(N)]
col = collections.LineCollection(xy, linewidths=linewidths)
if erase and self.lines:
for lc in self.lines:
lc.remove()
self.lines = []
self.lines.append(col)
col.set_color(colors)
self.ax.add_collection(col)
示例15: _add_solids
# 需要導入模塊: from matplotlib import collections [as 別名]
# 或者: from matplotlib.collections import LineCollection [as 別名]
def _add_solids(self, X, Y, C):
'''
Draw the colors using :meth:`~matplotlib.axes.Axes.pcolor`;
optionally add separators.
'''
## Change to pcolorfast after fixing bugs in some backends...
if self.extend in ["min", "both"]:
cc = self.to_rgba([C[0][0]])
self.extension_patch1.set_fc(cc[0])
X, Y, C = X[1:], Y[1:], C[1:]
if self.extend in ["max", "both"]:
cc = self.to_rgba([C[-1][0]])
self.extension_patch2.set_fc(cc[0])
X, Y, C = X[:-1], Y[:-1], C[:-1]
if self.orientation == 'vertical':
args = (X, Y, C)
else:
args = (np.transpose(Y), np.transpose(X), np.transpose(C))
kw = {'cmap':self.cmap, 'norm':self.norm,
'shading':'flat', 'alpha':self.alpha,
}
del self.solids
del self.dividers
col = self.ax.pcolor(*args, **kw)
self.solids = col
if self.drawedges:
self.dividers = collections.LineCollection(self._edges(X,Y),
colors=(mpl.rcParams['axes.edgecolor'],),
linewidths=(0.5*mpl.rcParams['axes.linewidth'],),
)
self.ax.add_collection(self.dividers)
else:
self.dividers = None