本文整理汇总了Python中matplotlib.collections.LineCollection.set_linewidths方法的典型用法代码示例。如果您正苦于以下问题:Python LineCollection.set_linewidths方法的具体用法?Python LineCollection.set_linewidths怎么用?Python LineCollection.set_linewidths使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.collections.LineCollection
的用法示例。
在下文中一共展示了LineCollection.set_linewidths方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def main(self):
x_field = self.fields_by_key('x')[0]
y_field = self.fields_by_key('y')[0]
x = np.array(self.slice_data(x_field,int))
y = np.array(self.slice_data(y_field,int))
n = len(x)
render = StringIO.StringIO()
###############################################################################
# Fit IsotonicRegression and LinearRegression models
ir = IsotonicRegression()
y_ = ir.fit_transform(x, y)
lr = LinearRegression()
lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression
###############################################################################
# plot result
segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(y)))
lc.set_linewidths(0.5 * np.ones(n))
fig = plt.figure()
plt.plot(x, y, 'r.', markersize=12)
plt.plot(x, y_, 'g.-', markersize=12)
plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')
plt.gca().add_collection(lc)
plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')
plt.title('Isotonic regression')
plt.savefig(render,format='png')
return render
示例2: plot_MDS
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def plot_MDS():
"""Plots the difference matrix with Multi-Dimensional Scaling"""
diff_matrix = fast_generate_diff_matrix()
X_true = diff_matrix
similarities = euclidean_distances(diff_matrix)
seed = 1
mds = manifold.MDS(n_components=1, max_iter=3000, eps=1e-9, random_state=seed,
dissimilarity="precomputed", n_jobs=1)
pos = mds.fit(similarities).embedding_
# nmds = manifold.MDS(n_components=2, metric=False, max_iter=3000, eps=1e-12,
# dissimilarity="precomputed", random_state=2, n_jobs=1,
# n_init=1)
# npos = nmds.fit_transform(similarities, init=pos)
# Rescale the data
pos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((pos ** 2).sum())
# npos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((npos ** 2).sum())
# Rotate the data
clf = PCA(n_components=2)
X_true = clf.fit_transform(X_true)
pos = clf.fit_transform(pos)
#
# npos = clf.fit_transform(npos)
fig = plt.figure(1)
ax = plt.axes([0., 0., 1., 1.])
plt.scatter(X_true[:, 0], X_true[:, 1], c='r', s=20)
# plt.scatter(pos[:, 0], pos[:, 1], s=20, c='g')
# plt.scatter(npos[:, 0], npos[:, 1], s=20, c='b')
plt.legend(('True position'), loc='best')
similarities = similarities.max() / similarities * 100
similarities[np.isinf(similarities)] = 0
# Plot the edges
start_idx, end_idx = np.where(pos)
#a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[X_true[i, :], X_true[j, :]]
for i in range(len(pos)) for j in range(len(pos))]
values = np.abs(similarities)
lc = LineCollection(segments,
zorder=0, cmap=plt.cm.hot_r,
norm=plt.Normalize(0, values.max()))
lc.set_array(similarities.flatten())
lc.set_linewidths(0.5 * np.ones(len(segments)))
ax.add_collection(lc)
plt.show()
示例3: visualize
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def visualize(reader, visualization_method, value_column, segment_column):
labels, data = organize_data(reader, visualization_method, value_column, segment_column)
if visualization_method == 'hc':
link = linkage(data)
dendrogram(link, leaf_label_func=lambda i: labels[i])
plt.gcf()
plt.show()
if visualization_method == 'mds':
n = len(labels)
data -= data.mean()
clf = PCA(n_components=2)
data = clf.fit_transform(data)
similarities = euclidean_distances(data)
# Add noise to the similarities
noise = np.random.rand(n, n)
noise = noise + noise.T
noise[np.arange(noise.shape[0]), np.arange(noise.shape[0])] = 0
similarities += noise
fig = plt.figure(1)
ax = plt.axes([0., 0., 1., 1.])
similarities = similarities.max() / similarities * 100
similarities[np.isinf(similarities)] = 0
plt.scatter(data[:, 0], data[:, 1], c='r', s=20)
plt.legend('Position', loc='best')
start_idx, end_idx = np.where(data)
segments = [[data[i, :], data[j, :]]
for i in range(len(data)) for j in range(len(data))]
values = np.abs(similarities)
lc = LineCollection(segments,
zorder=0, cmap=plt.cm.hot_r,
norm=plt.Normalize(0, values.max()))
lc.set_array(similarities.flatten())
lc.set_linewidths(0.5 * np.ones(len(segments)))
ax.add_collection(lc)
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy = (x, y), xytext = (-20, 20),
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
plt.show()
示例4: plotRegression
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def plotRegression(x, y, y_, lr):
segements = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segements, zorder=0)
lc.set_array(np.ones(len(y)))
lc.set_linewidths(0.5 * np.ones(n))
fig = plt.figure()
plt.plot(x, y, 'r.', markersize=12)
plt.plot(x, y_, 'g.-', markersize=12)
plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')
plt.gca().add_collection(lc)
plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')
plt.title('Isotonic regression')
plt.show()
示例5: Tracks
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
class Tracks(object):
def __init__(self, ax, tails=None):
self.tracks = None
self.tails = tails
self.initialize_lines(ax)
@staticmethod
def create_trackmap(stormdata):
trackmap = []
for trackid in range(np.max(stormdata['track_id']) + 1):
indexes = np.where(stormdata['track_id'] == trackid)[0]
# Makes sure the track segments are in chronological order
indexes = indexes[np.argsort(stormdata['frame_index'][indexes])]
trackmap.append(indexes)
return trackmap
def remove_lines(self):
if self.tracks is not None:
self.tracks.remove()
self.tracks = None
def initialize_lines(self, ax):
self.remove_lines()
self.tracks = LineCollection([])
ax.add_collection(self.tracks)
def update_lines(self, frame_index, stormdata):
segments = []
for indexes in self.create_trackmap(stormdata):
trackdata = stormdata[indexes]
trackdata = trackdata[trackdata['frame_index'] <= frame_index]
if self.tails:
mask = trackdata['frame_index'] >= (frame_index - self.tails)
trackdata = trackdata[mask]
# There must always be something in a track, even it it is NaNs.
segments.append(zip(trackdata['xcent'], trackdata['ycent'])
or [(np.nan, np.nan)])
self.tracks.set_segments(segments)
def lolite_line(self, indx):
self.hilite_line(indx, 1)
def hilite_line(self, indx, lw=4):
if indx is not None:
lws = self.tracks.get_linewidths()
lws[indx] = lw
self.tracks.set_linewidths(lws)
示例6: multidimensional_scaling
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def multidimensional_scaling(rdm, labels):
# perform multidimensional scaling
mds = MDS(
n_components=2,
max_iter=3000,
dissimilarity='precomputed'
)
positions = mds.fit(rdm).embedding_
positions /= positions.max()
# visualize the embedding in a figure
figure = plt.figure(1)
ax = plt.axes([0., 0., 1., 1.])
plt.scatter(positions[:, 0], positions[:, 1])
# plot the edges
segments = [[positions[i, :], positions[j, :]] for i in range(len(positions)) for j in range(len(positions))]
values = np.abs(rdm)
lc = LineCollection(
segments,
zorder=0,
cmap=plt.cm.YlGnBu,
norm=plt.Normalize(0, values.max())
)
lc.set_array(rdm.flatten())
lc.set_linewidths(2 * np.ones(len(segments)))
ax.add_collection(lc)
# add labels
for index, label in enumerate(labels):
plt.annotate(label, (positions[index, 0], positions[index, 1]))
plt.show()
示例7: HoughDemo
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
#.........这里部分代码省略.........
label=u"直线检测"
),
Group(
Item("dp", label=u"分辨率(像素)"),
Item("mindist", label=u"圆心最小距离(像素)"),
Item("param2", label=u"圆心检查阈值"),
Item("min_radius", label=u"最小半径"),
Item("max_radius", label=u"最大半径"),
label=u"圆检测"
),
Group(
Item("linewidth", label=u"线宽"),
Item("alpha", label=u"alpha"),
HGroup(
Item("check_line", label=u"直线"),
Item("check_circle", label=u"圆"),
),
label=u"绘图参数"
)
)
def __init__(self, **kwargs):
super(HoughDemo, self).__init__(**kwargs)
self.connect_dirty("th2, show_canny, show_blur, rho, theta, hough_th,"
"min_radius, max_radius, blur_sigma,"
"minlen, maxgap, dp, mindist, param2, "
"linewidth, alpha, check_line, check_circle")
self.lines = LineCollection([], linewidths=2, alpha=0.6)
self.axe.add_collection(self.lines)
self.circles = EllipseCollection(
[], [], [],
units="xy",
facecolors="none",
edgecolors="red",
linewidths=2,
alpha=0.6,
transOffset=self.axe.transData)
self.axe.add_collection(self.circles)
def _img_changed(self):
self.img_gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
def draw(self):
img_smooth = cv2.GaussianBlur(self.img_gray, (0, 0), self.blur_sigma, self.blur_sigma)
img_edge = cv2.Canny(img_smooth, self.th2 * 0.5, self.th2)
if self.show_blur and self.show_canny:
show_img = cv2.cvtColor(np.maximum(img_smooth, img_edge), cv2.COLOR_BAYER_BG2BGR)
elif self.show_blur:
show_img = cv2.cvtColor(img_smooth, cv2.COLOR_BAYER_BG2BGR)
elif self.show_canny:
show_img = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2BGR)
else:
show_img = self.img
if self.check_line:
theta = self.theta / 180.0 * np.pi
lines = cv2.HoughLinesP(img_edge,
self.rho, theta, self.hough_th,
minLineLength=self.minlen,
maxLineGap=self.maxgap)
if lines is not None:
lines = lines[0]
lines.shape = -1, 2, 2
self.lines.set_segments(lines)
self.lines.set_visible(True)
else:
self.lines.set_visible(False)
else:
self.lines.set_visible(False)
if self.check_circle:
circles = cv2.HoughCircles(img_smooth, 3,
self.dp, self.mindist,
param1=self.th2,
param2=self.param2,
minRadius=self.min_radius,
maxRadius=self.max_radius)
if circles is not None:
circles = circles[0]
self.circles._heights = self.circles._widths = circles[:, 2]
self.circles.set_offsets(circles[:, :2])
self.circles._angles = np.zeros(len(circles))
self.circles._transOffset = self.axe.transData
self.circles.set_visible(True)
else:
self.circles.set_visible(False)
else:
self.circles.set_visible(False)
self.lines.set_linewidths(self.linewidth)
self.circles.set_linewidths(self.linewidth)
self.lines.set_alpha(self.alpha)
self.circles.set_alpha(self.alpha)
self.draw_image(show_img)
示例8: getStockMarketStructure
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def getStockMarketStructure(symbol_dict):
# Choose a time period reasonnably calm (not too long ago so that we get
# high-tech firms, and before the 2008 crash)
d1 = datetime.datetime(2009, 1, 1)
d2 = datetime.datetime(2011, 1, 1)
#d1 = datetime.datetime.now() - timedelta(days=365*2)
#d2 = datetime.datetime.now()- timedelta(days=1)
# kraft symbol has now changed from KFT to MDLZ in yahoo
symbols, names = np.array(list(symbol_dict.items())).T
quotes = [finance.quotes_historical_yahoo(symbol, d1, d2, asobject=True)
for symbol in symbols]
open = np.array([q.open for q in quotes]).astype(np.float)
close = np.array([q.close for q in quotes]).astype(np.float)
# The daily variations of the quotes are what carry most information
variation = close - open
###############################################################################
# Learn a graphical structure from the correlations
edge_model = covariance.GraphLassoCV()
# standardize the time series: using correlations rather than covariance
# is more efficient for structure recovery
X = variation.copy().T
X /= X.std(axis=0)
edge_model.fit(X)
###############################################################################
# Cluster using affinity propagation
_, labels = cluster.affinity_propagation(edge_model.covariance_)
n_labels = labels.max()
for i in range(n_labels + 1):
print('Cluster %i: %s' % ((i + 1), ', '.join(names[labels == i])))
###############################################################################
# Find a low-dimension embedding for visualization: find the best position of
# the nodes (the stocks) on a 2D plane
# We use a dense eigen_solver to achieve reproducibility (arpack is
# initiated with random vectors that we don't control). In addition, we
# use a large number of neighbors to capture the large-scale structure.
node_position_model = manifold.LocallyLinearEmbedding(
n_components=2, eigen_solver='dense', n_neighbors=6)
embedding = node_position_model.fit_transform(X.T).T
###############################################################################
# Visualization
plt.figure(1, facecolor='w', figsize=(10, 8))
plt.clf()
ax = plt.axes([0., 0., 1., 1.])
plt.axis('off')
# Display a graph of the partial correlations
partial_correlations = edge_model.precision_.copy()
d = 1 / np.sqrt(np.diag(partial_correlations))
partial_correlations *= d
partial_correlations *= d[:, np.newaxis]
non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)
# Plot the nodes using the coordinates of our embedding
plt.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels,
cmap=plt.cm.spectral)
# Plot the edges
start_idx, end_idx = np.where(non_zero)
#a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[embedding[:, start], embedding[:, stop]]
for start, stop in zip(start_idx, end_idx)]
values = np.abs(partial_correlations[non_zero])
lc = LineCollection(segments,
zorder=0, cmap=plt.cm.hot_r,
norm=plt.Normalize(0, .7 * values.max()))
lc.set_array(values)
lc.set_linewidths(15 * values)
ax.add_collection(lc)
# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(
zip(names, labels, embedding.T)):
dx = x - embedding[0]
dx[index] = 1
dy = y - embedding[1]
dy[index] = 1
this_dx = dx[np.argmin(np.abs(dy))]
this_dy = dy[np.argmin(np.abs(dx))]
if this_dx > 0:
horizontalalignment = 'left'
x = x + .002
else:
horizontalalignment = 'right'
x = x - .002
if this_dy > 0:
verticalalignment = 'bottom'
y = y + .002
else:
#.........这里部分代码省略.........
示例9: SunPlotPy
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
#.........这里部分代码省略.........
self.canvas.draw()
def update_figure(self):
if self.autoclim:
self.clim = [self.data.min(),self.data.max()]
self.climlow.SetValue('%3.1f'%self.clim[0])
self.climhigh.SetValue('%3.1f'%self.clim[1])
else:
self.clim = [float(self.climlow.GetValue()),\
float(self.climhigh.GetValue())]
# check whether it is cell or edge type
if self.hasDim(self.variable,self.griddims['Ne']):
self.collectiontype='edges'
elif self.hasDim(self.variable,self.griddims['Nc']):
self.collectiontype='cells'
# Create a new figure if the variable has gone from cell to edge of vice
# versa
if not self.collectiontype==self.oldcollectiontype:
self.create_figure()
self.oldcollectiontype=self.collectiontype
self.collection.set_array(np.array(self.data[:]))
self.collection.set_clim(vmin=self.clim[0],vmax=self.clim[1])
# Cells only
if self.collectiontype=='cells':
if not self.showedges:
self.collection.set_edgecolors(self.collection.to_rgba(np.array((self.data[:]))))
else:
self.collection.set_edgecolors('k')
self.collection.set_linewidths(0.2)
# Update the title
self.title=self.axes.set_title(self.genTitle(),color=self.textcolor)
#Update the colorbar
self.cbar.update_normal(self.collection)
# redraw the figure
self.canvas.draw()
def on_pick(self, event):
# The event received here is of the type
# matplotlib.backend_bases.PickEvent
#
# It carries lots of information, of which we're using
# only a small amount here.
#
box_points = event.artist.get_bbox().get_points()
msg = "You've clicked on a bar with coords:\n %s" % box_points
dlg = wx.MessageDialog(
self,
msg,
"Click!",
wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def on_select_variable(self, event):
vname = event.GetString()
self.flash_status_message("Selecting variable: %s"%vname)
示例10: visualize
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def visualize(self, cluster=False, savefile=None, doshow=True, seed=None, node_labels=None, label_idx=None,
mark_nodes=False):
"""
Visualize the graph structure. The nodes positions are derived from the normalized PMI using the t-distributed
stochastic neighbors embedding, while the graph edges are derived from the normalized PMI values. To reduce
clutter, only those edges within top 5% of positive PMI values are drawn. The sizes of the nodes represent the
marginal frequencies of the features represented by each node.
:param cluster: If true, also cluster the nodes using affinity propagation and color them according to cluster
label.
:param savefile: The name of a file to save the figure to.
:param doshow: If true, then display the figure.
:param seed: The seed for the random number generator used for initialization of the t-distributed stochastic
neighbors embedding.
:param node_labels: A list of strings containing the labels for a set of nodes.
:param label_idx: The indices of the nodes to be labeled.
:param mark_nodes: If true, also mark the labeled nodes using a large green circle.
:return:
"""
if node_labels is None:
node_labels = []
if label_idx is None:
label_idx = []
if len(label_idx) != len(node_labels):
raise ValueError("Length of node_labels must be the same as label_idx.")
# use normalized PMI for similarity metric
similarity = self.pmi / -np.log(self.joint_probs)
similarity[np.diag_indices_from(similarity)] = 1.0
# compute the 2-d manifold and the projection of the data onto it. this defines the node positions
distance = -(similarity - 1.0) # convert to [-2.0, 0.0] and then make positive
node_position_model = manifold.TSNE(verbose=self.verbose, metric='precomputed', learning_rate=100,
random_state=seed)
node_positions = node_position_model.fit_transform(distance).T
if cluster:
# also include cluster information in the visualization
clusters = self.cluster(normalize=True)
plt.figure(1, facecolor='k', figsize=(10, 8))
plt.clf()
ax = plt.axes([0., 0., 1., 1.])
plt.axis('off')
# Plot the nodes using the coordinates of our embedding
base_symbol_size = self.train_marginal / float(self.train_marginal.max()) + 0.05
if cluster:
# color ingredient nodes by cluster
plt.scatter(node_positions[0], node_positions[1], s=300 * base_symbol_size, c=clusters,
cmap=plt.cm.spectral_r)
else:
plt.scatter(node_positions[0], node_positions[1], s=300 * base_symbol_size,
cmap=plt.cm.spectral_r, c='DodgerBlue')
# Display a graph of ingredients commonly found together based on pointwise mutual information (PMI)
non_zero = np.triu(similarity, k=1) > np.percentile(similarity[similarity > 0], 95.0)
start_idx, end_idx = np.where(non_zero)
#a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[node_positions[:, start], node_positions[:, stop]]
for start, stop in zip(start_idx, end_idx)]
values = similarity[non_zero]
lc = LineCollection(segments,
zorder=0, cmap=plt.cm.hot,
norm=plt.Normalize(values.min(), np.percentile(values, 95.0)))
lc.set_array(values)
lc.set_linewidths(2 * values)
ax.add_collection(lc)
# plt.colorbar(lc)
for label, node_idx in zip(node_labels, label_idx):
if mark_nodes:
plt.scatter(node_positions[0, node_idx], node_positions[1, node_idx], s=500, c='Green')
plt.text(node_positions[0, node_idx] + 0.02 * node_positions[0].ptp(),
node_positions[1, node_idx] + 0.02 * node_positions[1].ptp(),
label, size=20, color='White')
plt.xlim(node_positions[0].min() - .15 * node_positions[0].ptp(),
node_positions[0].max() + .10 * node_positions[0].ptp(),)
plt.ylim(node_positions[1].min() - .03 * node_positions[1].ptp(),
node_positions[1].max() + .03 * node_positions[1].ptp())
if savefile is not None:
plt.savefig(savefile, facecolor='k', edgecolor='Yellow')
if doshow:
plt.show()
return ax, node_positions
示例11: showCovariances
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def showCovariances(names,variation):
###############################################################################
# Learn a graphical structure from the correlations
edge_model = covariance.GraphLassoCV()
# standardize the time series: using correlations rather than covariance
# is more efficient for structure recovery
X = variation.copy().T
X /= X.std(axis=0)
edge_model.fit(X)
###############################################################################
# Cluster using affinity propagation
_, labels = cluster.affinity_propagation(edge_model.covariance_)
n_labels = labels.max()
for i in range(n_labels + 1):
print('Cluster %i: %s' % ((i + 1), ', '.join(names[labels == i])))
###############################################################################
# Find a low-dimension embedding for visualization: find the best position of
# the nodes (the stocks) on a 2D plane
# We use a dense eigen_solver to achieve reproducibility (arpack is
# initiated with random vectors that we don't control). In addition, we
# use a large number of neighbors to capture the large-scale structure.
node_position_model = manifold.LocallyLinearEmbedding(
n_components=2, eigen_solver='dense', n_neighbors=6)
embedding = node_position_model.fit_transform(X.T).T
###############################################################################
# Visualization
plt.figure(1, facecolor='w', figsize=(10, 8))
plt.clf()
ax = plt.axes([0., 0., 1., 1.])
plt.axis('off')
# Display a graph of the partial correlations
partial_correlations = edge_model.precision_.copy()
d = 1 / np.sqrt(np.diag(partial_correlations))
partial_correlations *= d
partial_correlations *= d[:, np.newaxis]
non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)
# Plot the nodes using the coordinates of our embedding
plt.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels,
cmap=plt.cm.spectral)
# Plot the edges
start_idx, end_idx = np.where(non_zero)
#a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[embedding[:, start], embedding[:, stop]]
for start, stop in zip(start_idx, end_idx)]
values = np.abs(partial_correlations[non_zero])
lc = LineCollection(segments,
zorder=0, cmap=plt.cm.hot_r,
norm=plt.Normalize(0, .7 * values.max()))
lc.set_array(values)
lc.set_linewidths(15 * values)
ax.add_collection(lc)
# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(
zip(names, labels, embedding.T)):
dx = x - embedding[0]
dx[index] = 1
dy = y - embedding[1]
dy[index] = 1
this_dx = dx[np.argmin(np.abs(dy))]
this_dy = dy[np.argmin(np.abs(dx))]
if this_dx > 0:
horizontalalignment = 'left'
x = x + .002
else:
horizontalalignment = 'right'
x = x - .002
if this_dy > 0:
verticalalignment = 'bottom'
y = y + .002
else:
verticalalignment = 'top'
y = y - .002
plt.text(x, y, name, size=10,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
bbox=dict(facecolor='w',
edgecolor=plt.cm.spectral(label / float(n_labels)),
alpha=.6))
plt.xlim(embedding[0].min() - .15 * embedding[0].ptp(),
embedding[0].max() + .10 * embedding[0].ptp(),)
plt.ylim(embedding[1].min() - .03 * embedding[1].ptp(),
embedding[1].max() + .03 * embedding[1].ptp())
#.........这里部分代码省略.........
示例12: check_random_state
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
x = np.arange(n)
rs = check_random_state(0)
y = rs.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n))
###############################################################################
# Fit IsotonicRegression and LinearRegression models
ir = IsotonicRegression()
y_ = ir.fit_transform(x, y)
lr = LinearRegression()
lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression
###############################################################################
# plot result
segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(y)))
lc.set_linewidths(0.5 * np.ones(n))
fig = plt.figure()
plt.plot(x, y, 'r.', markersize=12)
plt.plot(x, y_, 'g.-', markersize=12)
plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')
plt.gca().add_collection(lc)
plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')
plt.title('Isotonic regression')
plt.show()
示例13: plot_market_structure
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
def plot_market_structure(names, labels, embedding, partial_correlations):
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# Visualization
plt.figure(1, facecolor='w', figsize=(10, 8))
plt.clf()
ax = plt.axes([0., 0., 1., 1.])
plt.axis('off')
# Display a graph of the partial correlations
d = 1 / np.sqrt(np.diag(partial_correlations))
partial_correlations *= d
partial_correlations *= d[:, np.newaxis]
non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)
# Plot the nodes using the coordinates of our embedding
plt.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels,
cmap=plt.cm.spectral)
# Plot the edges
start_idx, end_idx = np.where(non_zero)
#a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[embedding[:, start], embedding[:, stop]]
for start, stop in zip(start_idx, end_idx)]
values = np.abs(partial_correlations[non_zero])
try:
lc = LineCollection(segments,
zorder=0, cmap=plt.cm.hot_r,
norm=plt.Normalize(0, .7 * values.max()))
lc.set_array(values)
lc.set_linewidths(8 * values)
except ValueError:
print "Warning: skip line normalization"
lc = LineCollection(segments,
zorder=0, cmap=plt.cm.hot_r)
lc.set_linewidths(1)
ax.add_collection(lc)
# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(
zip(names, labels, embedding.T)):
dx = x - embedding[0]
dx[index] = 1
dy = y - embedding[1]
dy[index] = 1
this_dx = dx[np.argmin(np.abs(dy))]
this_dy = dy[np.argmin(np.abs(dx))]
if this_dx > 0:
horizontalalignment = 'left'
x = x + .002
else:
horizontalalignment = 'right'
x = x - .002
if this_dy > 0:
verticalalignment = 'bottom'
y = y + .002
else:
verticalalignment = 'top'
y = y - .002
plt.text(x, y, name, size=10,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
color='black',
bbox=dict(facecolor='w',
edgecolor=plt.cm.spectral(label / float(labels.max())),
alpha=.6))
plt.xlim(embedding[0].min() - .15 * embedding[0].ptp(),
embedding[0].max() + .10 * embedding[0].ptp(),)
plt.ylim(embedding[1].min() - .03 * embedding[1].ptp(),
embedding[1].max() + .03 * embedding[1].ptp())
plt.show()
plt.close()
del plt, LineCollection
示例14: StockMarketOLD
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
#.........这里部分代码省略.........
_, labels = cluster.affinity_propagation(covariance_)
n_labels = labels.max()
for i in range(n_labels + 1):
print('Cluster %i: %s' % ((i + 1), ', '.join(symbols[labels == i])))
###############################################################################
# Find a low-dimension embedding for visualization: find the best position of
# the nodes (the stocks) on a 2D plane
# We use a dense eigen_solver to achieve reproducibility (arpack is
# initiated with random vectors that we don't control). In addition, we
# use a large number of neighbors to capture the large-scale structure.
node_position_model = manifold.LocallyLinearEmbedding(
n_components=2, eigen_solver='dense', n_neighbors=6)
embedding = node_position_model.fit_transform(X.T).T
###############################################################################
# Visualization
plt.figure(1, facecolor='w', figsize=(20, 16))
plt.clf()
ax = plt.axes([0., 0., 1., 1.])
plt.axis('off')
plt.annotate('From %s to %s' % (d1.strftime('%Y-%m-%d'),d2.strftime('%Y-%m-%d')),xy=(0.11,-0.37),size=25)
print X.shape
for i in range(n_labels + 1):
plt.annotate('Cluster %i: %s' % ((i + 1), ', '.join(symbols[labels == i])),xy=(-0.43,0.02-i*0.02),size=18)
pass
# Display a graph of the partial correlations
#partial_correlations = edge_model.precision_.copy()
partial_correlations = precision_.copy()
d = 1 / np.sqrt(np.diag(partial_correlations))
partial_correlations *= d
partial_correlations *= d[:, np.newaxis]
non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)
# Plot the nodes using the coordinates of our embedding
plt.scatter(embedding[0], embedding[1], s=200 * d ** 2, c=labels,
cmap=plt.cm.spectral)
# Plot the edges
start_idx, end_idx = np.where(non_zero)
#a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[embedding[:, start], embedding[:, stop]]
for start, stop in zip(start_idx, end_idx)]
values = np.abs(partial_correlations[non_zero])
lc = LineCollection(segments,
zorder=0, cmap=plt.get_cmap('Greys'),
norm=plt.Normalize(0, .7 * values.max()))
lc.set_array(values)
lc.set_linewidths(15 * values)
ax.add_collection(lc)
# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(
zip(names, labels, embedding.T)):
dx = x - embedding[0]
dx[index] = 1
dy = y - embedding[1]
dy[index] = 1
this_dx = dx[np.argmin(np.abs(dy))]
this_dy = dy[np.argmin(np.abs(dx))]
if this_dx > 0:
horizontalalignment = 'left'
x = x + .002
else:
horizontalalignment = 'right'
x = x - .002
if this_dy > 0:
verticalalignment = 'bottom'
y = y + .002
else:
verticalalignment = 'top'
y = y - .002
plt.text(x, y, name, size=22,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
bbox=dict(facecolor='w',
edgecolor=plt.cm.spectral(label / float(n_labels)),
alpha=.6))
plt.xlim(embedding[0].min() - .25 * embedding[0].ptp(),
embedding[0].max() + .20 * embedding[0].ptp(),)
plt.ylim(embedding[1].min() - .20 * embedding[1].ptp(),
embedding[1].max() + .20 * embedding[1].ptp())
plt.savefig('Graphs/StockCluster.pdf',bbox_inches='tight')
plt.savefig('Graphs/StockCluster.svg',bbox_inches='tight')
plt.show()
示例15: clusterSymbol
# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_linewidths [as 别名]
#.........这里部分代码省略.........
if 1 < len(names[labels==i]) <= 3:
# print 'random cluster ',np.random.choice(names[labels==i],3)
tmpdf = pd.DataFrame({'title':np.random.choice(names[labels==i],1)})
randomtitles = pd.concat([tmpdf, randomtitles])
elif 3 < len(names[labels==i]) <= 5:
tmpdf = pd.DataFrame({'title':np.random.choice(names[labels==i],2)})
randomtitles = pd.concat([tmpdf, randomtitles])
elif 5 < len(names[labels==i]) <= 7:
tmpdf = pd.DataFrame({'title':np.random.choice(names[labels==i],4)})
randomtitles = pd.concat([tmpdf, randomtitles])
elif 7 < len(names[labels==i]) :
tmpdf = pd.DataFrame({'title':np.random.choice(names[labels==i],5)})
randomtitles = pd.concat([tmpdf, randomtitles])
# print randomtitles
# for i in range(n_labels + 1):
# print 'Cluster '+str(i + 1)+', '+ names[labels == i]
# ###############################################################################
# Find a low-dimension embedding for visualization: find the best position of
# the nodes (the stocks) on a 2D plane
# We use a dense eigen_solver to achieve reproducibility (arpack is
# initiated with random vectors that we don't control). In addition, we
# use a large number of neighbors to capture the large-scale structure.
node_position_model = manifold.LocallyLinearEmbedding(
n_components=2, eigen_solver='dense', n_neighbors=6)
embedding = node_position_model.fit_transform(X.T).T
# ###############################################################################
# Visualization
pl.figure(1, facecolor='w', figsize=(15, 15))
pl.clf()
ax = pl.axes([0., 0., 1., 1.])
pl.axis('off')
# Display a graph of the partial correlations
partial_correlations = edge_model.precision_.copy()
d = 1 / np.sqrt(np.diag(partial_correlations))
partial_correlations *= d
partial_correlations *= d[:, np.newaxis]
non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)
# Plot the nodes using the coordinates of our embedding
pl.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels,
cmap=pl.cm.spectral)
# Plot the edges
start_idx, end_idx = np.where(non_zero)
#a sequence of (*line0*, *line1*, *line2*), where::
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[embedding[:, start], embedding[:, stop]]
for start, stop in zip(start_idx, end_idx)]
values = np.abs(partial_correlations[non_zero])
lc = LineCollection(segments,
zorder=0, cmap=pl.cm.hot_r,
norm=pl.Normalize(0, .7 * values.max()))
lc.set_array(values)
lc.set_linewidths(15 * values)
ax.add_collection(lc)
# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(
zip(names, labels, embedding.T)):
dx = x - embedding[0]
dx[index] = 1
dy = y - embedding[1]
dy[index] = 1
this_dx = dx[np.argmin(np.abs(dy))]
this_dy = dy[np.argmin(np.abs(dx))]
if this_dx > 0:
horizontalalignment = 'left'
x = x + .002
else:
horizontalalignment = 'right'
x = x - .002
if this_dy > 0:
verticalalignment = 'bottom'
y = y + .002
else:
verticalalignment = 'top'
y = y - .002
pl.text(x, y, name, size=10,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
bbox=dict(facecolor='w',
edgecolor=pl.cm.spectral(label / float(n_labels)),
alpha=.6))
pl.xlim(embedding[0].min() - .15 * embedding[0].ptp(),
embedding[0].max() + .10 * embedding[0].ptp(),)
pl.ylim(embedding[1].min() - .03 * embedding[1].ptp(),
embedding[1].max() + .03 * embedding[1].ptp())
pl.show()
return randomtitles