本文整理匯總了Python中matplotlib.patches.Patch方法的典型用法代碼示例。如果您正苦於以下問題:Python patches.Patch方法的具體用法?Python patches.Patch怎麽用?Python patches.Patch使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.patches
的用法示例。
在下文中一共展示了patches.Patch方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: graph_query_amounts
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def graph_query_amounts(captcha_queries, query_amounts):
queries_and_amounts = zip(captcha_queries, query_amounts)
queries_and_amounts = sorted(queries_and_amounts, key=lambda x:x[1], reverse=True)
captcha_queries, query_amounts = zip(*queries_and_amounts)
# colours = cm.Dark2(np.linspace(0,1,len(captcha_queries)))
# legend_info = zip(query_numbers, colours)
# random.shuffle(colours)
# captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries]
bars = plt.bar(left=range(len(query_amounts)), height=query_amounts)
plt.xlabel('CAPTCHA queries.')
plt.ylabel('Query frequencies.')
plt.xticks([])
# plt.xticks(range(len(captcha_queries)), captcha_queries, rotation='vertical')
# colours = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', ]
patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
plt.legend(handles=patches)
for i, bar in enumerate(bars):
bar.set_color(colours[i])
plt.show()
示例2: graph_correct_captchas
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def graph_correct_captchas(captcha_queries, correct_captchas):
queries_and_correct_scores = zip(captcha_queries, correct_captchas)
queries_and_correct_scores = sorted(queries_and_correct_scores, key=lambda x:x[1], reverse=True)
captcha_queries, correct_captchas = zip(*queries_and_correct_scores)
captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries]
bars = plt.bar(left=range(len(correct_captchas)), height=correct_captchas)
patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
plt.legend(handles=patches)
plt.xticks([])
for i, bar in enumerate(bars):
bar.set_color(colours[i])
plt.show()
# graph_correct_captchas(captcha_queries, correct_captchas)
# graph_query_amounts(captcha_queries, query_amounts)
示例3: _register_scatter
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def _register_scatter():
"""
Patch `PathCollection` and `scatter` to register their return values.
This registration allows us to distinguish `PathCollection`s created by
`Axes.scatter`, which should use point-like picking, from others, which
should use path-like picking. The former is more common, so we store the
latter instead; this also lets us guess the type better if this module is
imported late.
"""
@functools.wraps(PathCollection.__init__)
def __init__(self, *args, **kwargs):
_nonscatter_pathcollections.add(self)
return __init__.__wrapped__(self, *args, **kwargs)
PathCollection.__init__ = __init__
@functools.wraps(Axes.scatter)
def scatter(*args, **kwargs):
paths = scatter.__wrapped__(*args, **kwargs)
with suppress(KeyError):
_nonscatter_pathcollections.remove(paths)
return paths
Axes.scatter = scatter
示例4: add_legend_patch
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def add_legend_patch(self, legend_rows, fontsize=None):
if matplotlib.__version__ == '3.0.2':
self.logger.warning('skipping legend patch with matplotlib v3.0.2 for compatibility')
return
if self._legend is not None:
self._legend.remove()
self._legend = None
fontsize = fontsize or self.fontsize_scale
legend_bbox = self.figure.legend(
tuple(patches.Patch(color=patch_color) for patch_color, _ in legend_rows),
tuple(label for _, label in legend_rows),
borderaxespad=1.25,
fontsize=fontsize,
frameon=True,
handlelength=1.5,
handletextpad=0.75,
labelspacing=0.3,
loc='lower right'
)
legend_bbox.legendPatch.set_linewidth(0)
self._legend = legend_bbox
示例5: state
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def state(self):
img = np.copy(self.world[self.sight_range:self.world.shape[0]-self.sight_range,self.sight_range:self.world.shape[0]-self.sight_range])
img[img==0] = 256
img[img==1] = 215
img[img==2] = 123
img[img==3] = 175
img[img==9] = 1
p = plt.imshow(img, interpolation='nearest', cmap='nipy_spectral')
fig = plt.gcf()
c1 = mpatches.Patch(color='red', label='cats')
c2 = mpatches.Patch(color='green', label='mice')
c3 = mpatches.Patch(color='yellow', label='cheese')
plt.legend(handles=[c1,c2,c3],loc='center left',bbox_to_anchor=(1, 0.5))
#plt.savefig("cat_mouse%i.png" % self.gif, bbox_inches='tight')
#self.gif += 1
plt.pause(0.1)
# Run algorithm
示例6: set_color
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def set_color(self, c):
"""
Set the edgecolor.
Parameters
----------
c : color
Notes
-----
This method does not modify the facecolor (which defaults to "none"),
unlike the `Patch.set_color` method defined in the parent class. Use
`Patch.set_facecolor` to set the facecolor.
"""
self.set_edgecolor(c)
self.stale = True
示例7: plt_patch
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def plt_patch(node: minidom.Element, trans_parent_trans: mtransforms.Transform, style: dict, constructor: callable, ids: dict, no_draw: bool = False) -> mpatches.Patch:
""" add a node to the figure by calling the provided constructor """
trans_node = parseTransformation(node.getAttribute("transform"))
style = get_inline_style(node, get_css_style(node, ids["css"], style))
patch = constructor(node, trans_node + trans_parent_trans + plt.gca().transData, style, ids)
if not isinstance(patch, list):
patch = [patch]
for p in patch:
if not getattr(p, "is_marker", False):
style = apply_style(style, p)
p.style = style
#p.set_transform(p.get_transform() + plt.gca().transData)
p.trans_parent = trans_parent_trans
p.trans_node = parseTransformation(node.getAttribute("transform"))
if not no_draw and not styleNoDisplay(style):
plt.gca().add_patch(p)
if node.getAttribute("id") != "":
ids[node.getAttribute("id")] = patch
return patch
示例8: plot_phase_map
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def plot_phase_map(self, library, **kwargs):
phase_map = self.get_phase_map()
phase_name_index = get_phase_name_and_index(library)
plt.figure()
image = plt.imshow(phase_map)
colors = [image.cmap(image.norm(value)) for value in phase_name_index.values()]
patches = [
mpatches.Patch(
color=colors[i], label="{l}".format(l=list(library.keys())[i])
)
for i in range(len(phase_name_index.keys()))
]
plt.legend(handles=patches, bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.0)
plt.xlabel("x axis (nm)")
plt.ylabel("y axis (nm)")
plt.xticks([])
plt.yticks([])
plt.title("Phase map")
plt.tight_layout()
plt.show()
示例9: plot
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def plot(self):
try:
self.ax.cla()
except AttributeError:
self.ax = self.add_subplot(1, 1, 1, aspect=1.0)
for p in self.artists:
if isinstance(p, Line2D):
self.ax.add_line(p)
elif isinstance(p, Patch):
self.ax.add_patch(p)
else:
self.ax.add_artist(p)
self.scale_bounds(self.oversize_factor)
self.draw_frame(self.do_draw_frame)
self.ax.set_facecolor(backgrnd_color)
self.canvas.draw()
return self
示例10: draw_pianoroll
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def draw_pianoroll(pianoroll, name='Notes', show=False, save_path=''):
cm = matplotlib.cm.get_cmap('Greys')
notes_color = cm(1.0)
notes_patch = mpatches.Patch(color=notes_color, label=name)
plt.figure(figsize=(20.0, 10.0))
plt.title('Pianoroll Pitch-plot of ' + name, fontsize=10)
plt.legend(handles=[notes_patch], loc='upper right', prop={'size': 8})
plt.pcolor(pianoroll, cmap='Greys', vmin=0, vmax=np.max(pianoroll))
if show:
plt.show()
if len(save_path) > 0:
plt.savefig(save_path)
tikz_save(save_path + ".tex", encoding='utf-8', show_info=False)
plt.close()
示例11: compute_lsf
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def compute_lsf(self):
diff_esf = abs(self.esf[1:] - self.esf[0:(self.esf.shape[0] - 1)])
diff_esf = np.append(0, diff_esf)
lsf = diff_esf
diff_esf_smooth = abs(self.esf_smooth[0:(self.esf.shape[0] - 1)] - self.esf_smooth[1:])
diff_esf_smooth = np.append(0, diff_esf_smooth)
lsf_smooth = diff_esf_smooth
self.lsf = lsf
self.lsf_smooth = lsf_smooth
plt.subplot(2, 2, 3)
plt.title("LSF Curve")
plt.xlabel("pixel")
plt.ylabel("DN Value")
plt.plot(self.xesf, lsf, 'y-', self.xesf, lsf_smooth)
yellow_patch = mpatches.Patch(color='yellow', label='Raw LSF')
blue_patch = mpatches.Patch(color='blue', label='Smooth LSF')
plt.legend(handles=[yellow_patch, blue_patch])
self.compute_mtf()
示例12: compute_mtf
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def compute_mtf(self):
mtf = np.absolute(np.fft.fft(self.lsf, 2048))
mtf_smooth = np.absolute(np.fft.fft(self.lsf_smooth, 2048))
mtf_final = np.fft.fftshift(mtf)
mtf_final_smooth = np.fft.fftshift(mtf_smooth)
plt.subplot(2, 2, 4)
x_mtf_final = np.arange(0,1,1./127)
mtf_final = mtf_final[1024:1151]/np.amax(mtf_final[1024:1151])
mtf_final_smooth = mtf_final_smooth[1024:1151]/np.amax(mtf_final_smooth[1024:1151])
plt.plot(x_mtf_final, mtf_final, 'y-', x_mtf_final, mtf_final_smooth)
plt.xlabel("cycles/pixel")
plt.ylabel("Modulation Factor")
plt.title("MTF Curve")
yellow_patch = mpatches.Patch(color='yellow', label='Raw MTF')
blue_patch = mpatches.Patch(color='blue', label='Smooth MTF')
plt.legend(handles=[yellow_patch, blue_patch])
plt.show()
return mtf
示例13: train_val_curve
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def train_val_curve(train_loss, val_loss=None):
train_line = plt.plot(train_loss, label='train_loss')
train_patch = mpatches.Patch(color='blue',label='train_loss')
handles = [train_patch]
if val_loss:
val_line = plt.plot(val_loss, label='val_loss')
val_patch = mpatches.Patch(color='orange',label='val_loss')
handles.append(val_patch)
plt.legend(handles=handles, loc=2)
plt.title('training curves')
plt.ylabel('loss')
plt.xlabel('epochs')
plt.show()
# modified from the BaseLogger in file linked below
# https://github.com/fchollet/keras/blob/master/keras/callbacks.py
示例14: plot_many_results
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def plot_many_results(filenames, fn_beg_until="_", fn_end_from="_l_", save=True):
"""Plot files with similar beginning and ending filenames together."""
import matplotlib.pyplot as plt
figs = {}
for fn in filenames:
fn_beg = fn[:fn.find(fn_beg_until)]
fn_end = fn[fn.find(fn_end_from):]
fig_key = fn_beg, fn_end
if fig_key not in figs:
fig = plt.figure()
ax = plt.gca()
figs[fig_key] = (fig, {}, {})
fig, color_map, linestyle_map = figs[fig_key]
plot_result(fn, fig.axes[0], color_map, linestyle_map)
for fn_key, (fig, color_map, linestyle_map) in figs.items():
ax = fig.axes[0]
ax.set_title(fn_key)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel("size")
ax.set_ylabel("wallclock time (s)")
# add legend
patches = []
labels = []
import matplotlib.patches as mpatches
for key in sorted(color_map):
patches.append(mpatches.Patch(color=color_map[key]))
labels.append(key)
import matplotlib.lines as mlines
for key in sorted(linestyle_map):
patches.append(mlines.Line2D([], [], linestyle=linestyle_map[key], color='k'))
labels.append("{s:d} sectors".format(s=key))
ax.legend(patches, labels)
if save:
for key, (fig, _, _) in figs.items():
fn_beg, fn_end = key
fn = fn_beg + '_plot' + fn_end[:-4] + '.png'
fig.savefig(fn)
else:
plt.show()
示例15: plot_embedding
# 需要導入模塊: from matplotlib import patches [as 別名]
# 或者: from matplotlib.patches import Patch [as 別名]
def plot_embedding(X, y, d, title=None, save_fig=0, pname=None):
"""Plot an embedding X with the class label y colored by the domain d."""
x_min, x_max = np.min(X, 0), np.max(X, 0)
X = (X - x_min) / (x_max - x_min)
# Plot colors numbers
plt.figure(figsize=(10,10))
ax = plt.subplot(111)
for i in range(X.shape[0]):
# plot colored number
# plt.text(X[i, 0], X[i, 1], str(y[i]),
# color=plt.cm.bwr(d[i] / 1.),
# fontdict={'weight': 'bold', 'size': 9})
if d[i]==0:
c = 'red'
elif d[i]==1:
c = 'green'
elif d[i]==2:
c = 'blue'
plt.text(X[i, 0], X[i, 1], str(y[i]),
color= c,
fontdict={'weight': 'bold', 'size': 9})
plt.xticks([]), plt.yticks([])
red_patch = mpatches.Patch(color='red', label='Source data')
green_patch = mpatches.Patch(color='green', label='Target data')
plt.legend(handles=[red_patch, green_patch])
plt.show()
if title is not None:
plt.title(title)
if save_fig:
fname = title+'.png'
if pname is not None:
fname = os.path.join(pname, fname)
plt.savefig(fname)