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',
snap=True) # added snap=True
#-----------------------------------------------
# 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.pcolor(*args, **kw) # was pcolormesh
#-----------------------------------------------
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)
python类LineCollection()的实例源码
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 = [list(zip(X[i], Y[i])) for i in xrange(N)]
else:
xy = [list(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)
def drawcounties(self,linewidth=0.1,linestyle='solid',color='k',antialiased=1,
ax=None,zorder=None,drawbounds=False):
"""
Draw county boundaries in US. The county boundary shapefile
originates with the NOAA Coastal Geospatial Data Project
(http://coastalgeospatial.noaa.gov/data_gis.html).
.. tabularcolumns:: |l|L|
============== ====================================================
Keyword Description
============== ====================================================
linewidth county boundary line width (default 0.1)
linestyle coastline linestyle (default solid)
color county boundary line color (default black)
antialiased antialiasing switch for county boundaries
(default True).
ax axes instance (overrides default axes instance)
zorder sets the zorder for the county boundaries (if not
specified, uses default zorder for
matplotlib.patches.LineCollections).
============== ====================================================
returns a matplotlib.patches.LineCollection object.
"""
ax = ax or self._check_ax()
gis_file = os.path.join(basemap_datadir,'UScounties')
county_info = self.readshapefile(gis_file,'counties',\
default_encoding='latin-1',drawbounds=drawbounds)
counties = [coords for coords in self.counties]
counties = LineCollection(counties)
counties.set_linestyle(linestyle)
counties.set_linewidth(linewidth)
counties.set_color(color)
counties.set_label('counties')
if zorder:
counties.set_zorder(zorder)
ax.add_collection(counties)
return counties
def plotTrajectory(data):
# points = np.array([x, y]).T.reshape(-1, 1, 2)
# segments = np.concatenate([points[:-1], points[1:]], axis=1)
#
# lc = LineCollection(segments, cmap=plt.get_cmap('Spectral'))
# lc.set_array(z)
# #lc.set_linewidth(2)
#
# plt.gca().add_collection(lc)
import matplotlib.cm as cm
cmap = cm.jet;
c = np.linspace(0, 10, len(data[:,0]));
plt.scatter(data[:,0], data[:,1], c = c, cmap = cmap, marker = '+');
def plot_colored_line(x,y, color, cmap = 'spectral_r', line_width = 2):
"""Plot a line with color code"""
segments = np.array([x, y]).T.reshape(-1, 1, 2);
segments = np.concatenate([segments[:-1], segments[1:]], axis=1);
lc = LineCollection(segments, cmap=cmap);
lc.set_array(np.array(color));
#lc.set_linewidth(line_width);
plt.gca().add_collection(lc)
def plot_colored_line(x,y, color, cmap = 'spectral_r', line_width = 2):
"""Plot a line with color code"""
segments = np.array([x, y]).T.reshape(-1, 1, 2);
segments = np.concatenate([segments[:-1], segments[1:]], axis=1);
lc = LineCollection(segments, cmap=cmap);
lc.set_array(np.array(color));
#lc.set_linewidth(line_width);
plt.gca().add_collection(lc)
def _animate(fig, ax, frame_data, line_width=2, fps=10, tail_color='r',
tail_alpha=0.75, head_color='b', head_alpha=1):
segments, segment_frames, timestamps, fade_frames = frame_data
head_color = np.array(to_rgb(head_color))[None]
tail_color = np.array(to_rgb(tail_color))[None]
# start with all segments transparent
segment_colors = np.zeros((len(segments), 4), dtype=float)
lines = LineCollection(segments, linewidths=line_width, colors=segment_colors)
ax.add_collection(lines)
timer = ax.text(1, 0, '0:00:00', transform=ax.transAxes, zorder=3,
verticalalignment='bottom', horizontalalignment='right',
bbox=dict(facecolor='white'))
def update_frame(frame_idx):
frame_diff = frame_idx - segment_frames
mask = frame_diff < 0
# compute head alpha
alpha1 = 1 - np.minimum(frame_diff/fade_frames, 1)
alpha1[mask] = 0
alpha1 *= head_alpha
# compute tail alpha
alpha2 = (1 - mask) * tail_alpha
# composite alpha and colors
color, alpha = _blend_alpha(head_color, alpha1, tail_color, alpha2)
segment_colors[:, :3] = color
segment_colors[:, 3] = alpha
lines.set_color(segment_colors)
timer.set_text(timestamps[frame_idx])
return lines, timer
interval = 1000. / fps
return FuncAnimation(fig, update_frame, frames=len(timestamps), blit=True,
interval=interval, repeat=True)
def plot_edges(pts, edges, title=None, clabel=None,
save=None, show=True):
nppts = np.array(pts)
npedges = np.array(edges)
lc = LineCollection(nppts[npedges])
fig = Figure(title=title, clabel=clabel, save=save, show=show)
fig.ax.add_collection(lc)
plt.xlim(nppts[:, 0].min(), nppts[:, 0].max())
plt.ylim(nppts[:, 1].min(), nppts[:, 1].max())
plt.plot(nppts[:, 0], nppts[:, 1], 'ro')
return fig
def __init__(self, plotman):
self.plotman = plotman
self.axes = plotman.axes
self.mode_colors = plotman.mode_colors
# create a blank invariant violation polys
self.inv_vio_polys = collections.PolyCollection([], animated=True, alpha=0.7, edgecolor='red', facecolor='red')
self.axes.add_collection(self.inv_vio_polys)
# create a blank currently-tracked set of states poly
self.cur_state_line2d = Line2D([], [], animated=True, color='k', lw=2, mew=2, ms=5, fillstyle='none')
self.axes.add_line(self.cur_state_line2d)
self.parent_to_polys = OrderedDict()
self.parent_to_markers = OrderedDict()
self.waiting_list_mode_to_polys = OrderedDict()
self.aggregation_mode_to_polys = OrderedDict()
self.trace = collections.LineCollection(
[[(0, 0)]], animated=True, colors=('k'), linewidths=(3), linestyle='dashed')
self.axes.add_collection(self.trace)
if plotman.settings.extra_lines is not None:
lines = plotman.settings.extra_lines
self.extra_lines_col = collections.LineCollection(
lines, animated=True, colors=('gray'), linewidths=(2), linestyle='dashed')
self.axes.add_collection(self.extra_lines_col)
else:
self.extra_lines_col = None
self.freeze_attrs()
def plotGraph(self, pltax, offset0 = [600, -800], offset1 = [600, 800]):
self.regghalf[0].plotGraph(pltax, offset0)
self.regghalf[1].plotGraph(pltax, offset1)
# # add offset
for nid in self.gnodesplotpos.keys():
if nid.startswith('assrgt'):
self.gnodesplotpos[nid] = map(add, self.gnodesplotpos[nid], [offset0[0], 0])
if nid.startswith('asslft'):
self.gnodesplotpos[nid] = map(add, self.gnodesplotpos[nid], [offset1[0], 0])
# make composed gnodesplotpos
self.composedgnodesplotpos = {}
for key in self.gnodesplotpos.keys():
self.composedgnodesplotpos[key] = self.gnodesplotpos[key]
for key in self.regghalf[0].gnodesplotpos.keys():
self.composedgnodesplotpos[key] = self.regghalf[0].gnodesplotpos[key]
for key in self.regghalf[0].graphtpp.gnodesplotpos.keys():
self.composedgnodesplotpos[key] = self.regghalf[0].graphtpp.gnodesplotpos[key]
for key in self.regghalf[1].gnodesplotpos.keys():
self.composedgnodesplotpos[key] = self.regghalf[1].gnodesplotpos[key]
for key in self.regghalf[1].graphtpp.gnodesplotpos.keys():
self.composedgnodesplotpos[key] = self.regghalf[1].graphtpp.gnodesplotpos[key]
transitedges = []
transferedges = []
for nid0, nid1, reggedgedata in self.regg.edges(data=True):
if reggedgedata['edgetype'] is 'asstransit':
transitedges.append([self.composedgnodesplotpos[nid0][:2], self.composedgnodesplotpos[nid1][:2]])
if reggedgedata['edgetype'] is 'asstransfer':
transferedges.append([self.composedgnodesplotpos[nid0][:2], self.composedgnodesplotpos[nid1][:2]])
transitec = mc.LineCollection(transitedges, colors=[1,0,1,1], linewidths=1)
transferec = mc.LineCollection(transferedges, colors=[.5,.5,0,.03], linewidths=1)
pltax.add_collection(transferec)
pltax.add_collection(transitec)
def displayGraph2( nbPillar,g,r, lw):
x1 = []
x2 = []
y1 = []
y2 = []
lines = []
c = []
d2 = copy.deepcopy(g)
while len(d2) > 0:
n1 = d2.keys()[0]
n2 = d2[n1].keys()[0]
c1 = pillar2tocart(n1,nbPillar,r)
c2 = pillar2tocart(n2,nbPillar,r)
#x1.append(c1[0])
#x2.append(c2[0])
#y1.append(c1[1])
#y2.append(c2[1])
lines.append(((c1[0],-c1[1]),(c2[0],-c2[1])))
c.append( (0,0,0,1) )
decreaseWeightEdge(d2,n1,n2)
#lines = plt.plot( np.stack(x1),np.stack(y1),np.stack(x2),np.stack(y2))
#plt.setp(lines, color='white', linewidth=1.0)
#plt.gca().set_axis_bgcolor('black')
lc = mc.LineCollection(lines,colors=np.array(c) ,linewidths=lw)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
fig.show()
#plt.show()
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`.
.. versionadded:: 0.6.0
Parameters
----------
ax : :class:`matplotlib:matplotlib.axes.Axes`
lines : nested :class:`numpy:numpy.ndarray` 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)
def rgbline(ax, k, e, red, green, blue, alpha=1.):
# creation of segments based on
# http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb
pts = np.array([k, e]).T.reshape(-1, 1, 2)
seg = np.concatenate([pts[:-1], pts[1:]], axis=1)
nseg = len(k) - 1
r = [0.5 * (red[i] + red[i + 1]) for i in range(nseg)]
g = [0.5 * (green[i] + green[i + 1]) for i in range(nseg)]
b = [0.5 * (blue[i] + blue[i + 1]) for i in range(nseg)]
a = np.ones(nseg, np.float) * alpha
lc = LineCollection(seg, colors=list(zip(r, g, b, a)), linewidth=2)
ax.add_collection(lc)
def _update_channels_epochs(event, params):
"""Function for changing the amount of channels and epochs per view."""
from matplotlib.collections import LineCollection
# Channels
n_channels = int(np.around(params['channel_slider'].val))
offset = params['ax'].get_ylim()[0] / n_channels
params['offsets'] = np.arange(n_channels) * offset + (offset / 2.)
while len(params['lines']) > n_channels:
params['ax'].collections.pop()
params['lines'].pop()
while len(params['lines']) < n_channels:
lc = LineCollection(list(), linewidths=0.5, antialiased=False,
zorder=3, picker=3.)
params['ax'].add_collection(lc)
params['lines'].append(lc)
params['ax'].set_yticks(params['offsets'])
params['vsel_patch'].set_height(n_channels)
params['n_channels'] = n_channels
# Epochs
n_epochs = int(np.around(params['epoch_slider'].val))
n_times = len(params['epochs'].times)
ticks = params['epoch_times'] + 0.5 * n_times
params['ax2'].set_xticks(ticks[:n_epochs])
params['n_epochs'] = n_epochs
params['duration'] = n_times * n_epochs
params['hsel_patch'].set_width(params['duration'])
params['data'] = np.zeros((len(params['data']), params['duration']))
if params['t_start'] + n_times * n_epochs > len(params['times']):
params['t_start'] = len(params['times']) - n_times * n_epochs
params['hsel_patch'].set_x(params['t_start'])
params['plot_update_proj_callback'](params)
def make_segments(x, y):
"""
Create list of line segments from x and y coordinates, in the correct
format for LineCollection:
an array of the form numlines x (points per line) x 2 (x and y) array
"""
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
return segments
# Read in the merged data file
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
def cie_1931_wavelength_annotations(wavelengths, fig=None, ax=None):
''' Draws lines normal to the spectral locust on a CIE 1931 diagram and
writes the text for each wavelength.
Args:
wavelengths (`iterable`): set of wavelengths to annotate.
fig (`matplotlib.figure.Figure`): figure to draw on.
ax (`matplotlib.axes.Axis`): axis to draw in.
Returns:
`tuple` containing:
`matplotlib.figure.Figure`: figure containing the annotations.
`matplotlib.axes.Axis`: axis containing the annotations.
Notes:
see SE:
https://stackoverflow.com/questions/26768934/annotation-along-a-curve-in-matplotlib
'''
# some tick parameters
tick_length = 0.025
text_offset = 0.06
# convert wavelength to u' v' coordinates
wavelengths = np.asarray(wavelengths)
idx = np.arange(1, len(wavelengths) - 1, dtype=int)
wvl_lbl = wavelengths[idx]
xy = XYZ_to_xy(wavelength_to_XYZ(wavelengths))
x, y = xy[..., 0][idx], xy[..., 1][idx]
x_last, y_last = xy[..., 0][idx - 1], xy[..., 1][idx - 1]
x_next, y_next = xy[..., 0][idx + 1], xy[..., 1][idx + 1]
angle = atan2(y_next - y_last, x_next - x_last) + pi / 2
cos_ang, sin_ang = cos(angle), sin(angle)
x1, y1 = x + tick_length * cos_ang, y + tick_length * sin_ang
x2, y2 = x + text_offset * cos_ang, y + text_offset * sin_ang
fig, ax = share_fig_ax(fig, ax)
tick_lines = LineCollection(np.c_[x, y, x1, y1].reshape(-1, 2, 2), color='0.25', lw=1.25)
ax.add_collection(tick_lines)
for i in range(len(idx)):
ax.text(x2[i], y2[i], str(wvl_lbl[i]), va="center", ha="center", clip_on=True)
return fig, ax
def cie_1976_wavelength_annotations(wavelengths, fig=None, ax=None):
''' Draws lines normal to the spectral locust on a CIE 1976 diagram and
writes the text for each wavelength.
Args:
wavelengths (`iterable`): set of wavelengths to annotate.
fig (`matplotlib.figure.Figure`): figure to draw on.
ax (`matplotlib.axes.Axis`): axis to draw in.
Returns:
`tuple` containing:
`matplotlib.figure.Figure`: figure containing the annotations.
`matplotlib.axes.Axis`: axis containing the annotations.
Notes:
see SE:
https://stackoverflow.com/questions/26768934/annotation-along-a-curve-in-matplotlib
'''
# some tick parameters
tick_length = 0.025
text_offset = 0.06
# convert wavelength to u' v' coordinates
wavelengths = np.asarray(wavelengths)
idx = np.arange(1, len(wavelengths) - 1, dtype=int)
wvl_lbl = wavelengths[idx]
uv = XYZ_to_uvprime(wavelength_to_XYZ(wavelengths))
u, v = uv[..., 0][idx], uv[..., 1][idx]
u_last, v_last = uv[..., 0][idx - 1], uv[..., 1][idx - 1]
u_next, v_next = uv[..., 0][idx + 1], uv[..., 1][idx + 1]
angle = atan2(v_next - v_last, u_next - u_last) + pi / 2
cos_ang, sin_ang = cos(angle), sin(angle)
u1, v1 = u + tick_length * cos_ang, v + tick_length * sin_ang
u2, v2 = u + text_offset * cos_ang, v + text_offset * sin_ang
fig, ax = share_fig_ax(fig, ax)
tick_lines = LineCollection(np.c_[u, v, u1, v1].reshape(-1, 2, 2), color='0.25', lw=1.25)
ax.add_collection(tick_lines)
for i in range(len(idx)):
ax.text(u2[i], v2[i], str(wvl_lbl[i]), va="center", ha="center", clip_on=True)
return fig, ax
def draw_group(data, panel_params, coord, ax, **params):
data = coord.transform(data, panel_params)
data['size'] *= SIZE_FACTOR
has_x = 'x' in data.columns
has_y = 'y' in data.columns
if has_x or has_y:
n = len(data)
else:
return
rugs = []
sides = params['sides']
xmin, xmax = panel_params['x_range']
ymin, ymax = panel_params['y_range']
xheight = (xmax-xmin)*0.03
yheight = (ymax-ymin)*0.03
if has_x:
if 'b' in sides:
x = np.repeat(data['x'].values, 2)
y = np.tile([ymin, ymin+yheight], n)
rugs.extend(make_line_segments(x, y, ispath=False))
if 't' in sides:
x = np.repeat(data['x'].values, 2)
y = np.tile([ymax-yheight, ymax], n)
rugs.extend(make_line_segments(x, y, ispath=False))
if has_y:
if 'l' in sides:
x = np.tile([xmin, xmin+xheight], n)
y = np.repeat(data['y'].values, 2)
rugs.extend(make_line_segments(x, y, ispath=False))
if 'r' in sides:
x = np.tile([xmax-xheight, xmax], n)
y = np.repeat(data['y'].values, 2)
rugs.extend(make_line_segments(x, y, ispath=False))
color = to_rgba(data['color'], data['alpha'])
coll = mcoll.LineCollection(rugs,
edgecolor=color,
linewidth=data['size'],
linestyle=data['linetype'],
zorder=params['zorder'])
ax.add_collection(coll)
def _colorline(ax, x, y, color = (0, 0, 0), **kwargs):
'''
Plots the curve `y(x)` with linearly increasing alpha.
Adapted from `http://nbviewer.jupyter.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb`_.
'''
# A bit hacky... But there doesn't seem to be
# an easy way to get the hex code for a named color...
if isinstance(color, string_types):
if color.startswith("#"):
hex = color[1:]
else:
if len(color) == 1:
if color == 'k':
color = 'black'
elif color == 'r':
color = 'red'
elif color == 'b':
color = 'blue'
elif color == 'g':
color = 'green'
elif color == 'y':
color = 'yellow'
elif color == 'w':
color = 'white'
else:
# ?!
color = 'black'
hex = matplotlib.colors.cnames[color.lower()][1:]
r, g, b = tuple(int(hex[i:i+2], 16) / 255. for i in (0, 2, 4))
else:
r, g, b = color
colors = [(r, g, b, i) for i in np.linspace(0, 1, 3)]
cmap = LinearSegmentedColormap.from_list('alphacmap', colors, N = 1000)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, array = np.linspace(0.0, 1.0, len(x)),
cmap = cmap, norm = pl.Normalize(0.0, 1.0), **kwargs)
ax.add_collection(lc)
return lc