本文整理汇总了Python中matplotlib.lines.Line2D方法的典型用法代码示例。如果您正苦于以下问题:Python lines.Line2D方法的具体用法?Python lines.Line2D怎么用?Python lines.Line2D使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.lines
的用法示例。
在下文中一共展示了lines.Line2D方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: newline
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def newline(p1, p2, color=None, marker=None):
"""
https://stackoverflow.com/questions/36470343/how-to-draw-a-line-with-matplotlib
:param p1:
:param p2:
:return:
"""
ax = plt.gca()
xmin, xmax = ax.get_xbound()
if (p2[0] == p1[0]):
xmin = xmax = p1[0]
ymin, ymax = ax.get_ybound()
else:
ymax = p1[1] + (p2[1] - p1[1]) / (p2[0] - p1[0]) * (xmax - p1[0])
ymin = p1[1] + (p2[1] - p1[1]) / (p2[0] - p1[0]) * (xmin - p1[0])
l = mlines.Line2D([xmin, xmax], [ymin, ymax], color=color, marker=marker)
ax.add_line(l)
return l
示例2: addCanvasDashedWedge
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def addCanvasDashedWedge(self, p1, p2, p3, dash=(2, 2), color=(0, 0, 0), color2=None, **kwargs):
canvas = self._axes
dash = (3, 3)
pts1 = self._getLinePoints(p1, p2, dash)
pts2 = self._getLinePoints(p1, p3, dash)
pts1 = [self.rescalePt(p) for p in pts1]
pts2 = [self.rescalePt(p) for p in pts2]
if len(pts2) < len(pts1):
pts2, pts1 = pts1, pts2
for i in range(len(pts1)):
if color2 and color2 != color:
mp = (pts1[i][0] + pts2[i][0]) / 2., (pts1[i][1] + pts2[i][1]) / 2.
canvas.add_line(Line2D((pts1[i][0], mp[0]), (pts1[i][1], mp[1]), color=color, **kwargs))
canvas.add_line(Line2D((mp[0], pts2[i][0]), (mp[1], pts2[i][1]), color=color2, **kwargs))
else:
canvas.add_line(
Line2D((pts1[i][0], pts2[i][0]), (pts1[i][1], pts2[i][1]), color=color, **kwargs))
示例3: _add_opacity_legend
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def _add_opacity_legend(ax=None):
"""Add legend to an opacity lookup table plot."""
if ax is None:
ax = plt.gca()
blue_line = Line2D([], [], label='species opacity')
black_line = Line2D([], [], color='k', linewidth=1.,
label='total opacity')
dashed_line = Line2D([], [], color='k', linestyle='--',
linewidth=1., label='opacity=1')
handles = [blue_line, black_line, dashed_line]
labels = [h.get_label() for h in handles]
ax.legend(handles=handles, labels=labels, fontsize='xx-small',
loc='upper left', ncol=6)
示例4: _add_xsec_legend
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def _add_xsec_legend(lookup, ipressures, ax=None):
"""Add legend to a cross section lookup table plot."""
if ax is None:
ax = plt.gca()
pgrid = lookup.pressuregrid
colors = [plt.cm.viridis(i) for i in np.linspace(0, 1, len(ipressures))]
handles = [Line2D([], [],
color=colors[i],
label=f'{pgrid[ip]/100.:8.3f} hPa')
for i, ip in enumerate(ipressures)]
labels = [h.get_label() for h in handles]
ax.legend(handles=handles, labels=labels, fontsize='xx-small',
loc='upper left', ncol=6)
示例5: add_legend_patch
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [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
legend_bbox = self.figure.legend(
tuple(lines.Line2D([], [], color=patch_color, lw=3, ls=style) for patch_color, style, _ in legend_rows),
tuple(label for _, _, label in legend_rows),
borderaxespad=1,
columnspacing=1.5,
fontsize=self.fontsize_scale,
ncol=3,
frameon=True,
handlelength=2,
handletextpad=0.5,
labelspacing=0.5,
loc='upper right'
)
legend_bbox.get_frame().set_facecolor(self.get_color('line_bg', ColorHexCode.GRAY))
for text in legend_bbox.get_texts():
text.set_color('white')
legend_bbox.legendPatch.set_linewidth(0)
self._legend = legend_bbox
示例6: add_click
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def add_click(self, event):
"""
This add the coordinates of an event to the list of clicks
"""
self.clicks.append((event.xdata, event.ydata))
verbose.report("input %i: %f,%f" %
(len(self.clicks), event.xdata, event.ydata))
# If desired plot up click
if self.show_clicks:
line = mlines.Line2D([event.xdata], [event.ydata],
marker='+', color='r')
event.inaxes.add_line(line)
self.marks.append(line)
self.fig.canvas.draw()
示例7: _gen_axes_spines
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'):
"""
Returns
-------
dict
Mapping of spine names to `Line2D` or `Patch` instances that are
used to draw axes spines.
In the standard axes, spines are single line segments, but in other
projections they may not be.
Notes
-----
Intended to be overridden by new projection types.
"""
return OrderedDict((side, mspines.Spine.linear_spine(self, side))
for side in ['left', 'right', 'bottom', 'top'])
示例8: addCanvasLine
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def addCanvasLine(self, p1, p2, color=(0, 0, 0), color2=None, **kwargs):
canvas = self._axes
p1 = self.rescalePt(p1)
p2 = self.rescalePt(p2)
if color2 and color2 != color:
mp = (p1[0] + p2[0]) / 2., (p1[1] + p2[1]) / 2.
canvas.add_line(Line2D((p1[0], mp[0]), (p1[1], mp[1]), color=color, **kwargs))
canvas.add_line(Line2D((mp[0], p2[0]), (mp[1], p2[1]), color=color2, **kwargs))
else:
canvas.add_line(Line2D((p1[0], p2[0]), (p1[1], p2[1]), color=color, **kwargs))
示例9: plot_many_results
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [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()
示例10: plot_costs
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def plot_costs(case, number_of_segments=1, ax=None, legend=True):
if ax is None:
fig, axs = plt.subplots(1, 1, figsize=(16, 10))
ax = axs
color_scale = make_interpolater(0, len(case.gen_name), 0, 1)
color = {g: plt.cm.jet(color_scale(i)) for i, g in enumerate(case.gen_name)}
for s in calculate_segments(case, number_of_segments=number_of_segments):
pmin, pmax = s['segment']
x = np.linspace(pmin, pmax)
y = x * s['slope']
ax.plot(x, y, color=color[s['name']])
ax = ax.twinx()
for s in calculate_segments(case, number_of_segments=number_of_segments):
pmin, pmax = s['segment']
x = np.linspace(pmin, pmax)
y = [s['slope'] for _ in x]
ax.plot(x, y, color=color[s['name']])
ax.set_ylim(0, 1.2*y[-1])
if legend:
lines = list()
for g in case.gen_name:
lines.append(mlines.Line2D([], [], color=color[g], label=g))
ax.legend(handles=lines, loc='upper left')
return ax
示例11: plot_polygon_outlines
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def plot_polygon_outlines(self,polygons, colour='black', linewidth=1, alpha = 1, legend=False, label=""):
"""
This function plots an outline of a series of shapely polygons
Modified to also plot shapely Multipolygons if passed.
Added ability to create legend item
Args:
ax_list: list of axes
polygons: dict of shapely polygons
Author: FJC
"""
from shapely.geometry import Polygon, MultiPolygon
print('Plotting the polygon outlines...')
for key, poly in polygons.items():
if poly.geom_type == 'Polygon':
x,y = poly.exterior.xy
self.ax_list[0].plot(x,y, c=colour, lw = linewidth, alpha = alpha)
elif poly.geom_type == 'MultiPolygon':
for singlepoly in poly:
x,y = singlepoly.exterior.xy
self.ax_list[0].plot(x,y, c=colour, lw = linewidth, alpha = alpha)
# get legend handles
if legend:
print("Trying to update legend!")
legend_line = mlines.Line2D([],[], color=colour, lw=linewidth, label=label)
self.legend_handles_list.append(legend_line)
示例12: overlap
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def overlap(ax, bbox, get_vertices=False):
"""
Find overlap of bbox for drawn elements an axes.
"""
from matplotlib.lines import Line2D
from matplotlib.patches import Patch, Rectangle
# From
# https://github.com/matplotlib/matplotlib/blob/08008d5cb4d1f27692e9aead9a76396adc8f0b19/lib/matplotlib/legend.py#L845
lines = []
bboxes = []
for handle in ax.lines:
assert isinstance(handle, Line2D)
path = handle.get_path()
lines.append(path)
for handle in ax.collections:
for path in handle.get_paths():
lines.append(path.interpolated(20))
for handle in ax.patches:
assert isinstance(handle, Patch)
if isinstance(handle, Rectangle):
transform = handle.get_data_transform()
bboxes.append(handle.get_bbox().transformed(transform))
else:
transform = handle.get_transform()
bboxes.append(handle.get_path().get_extents(transform))
# TODO Possibly other objects
vertices = np.concatenate([line.vertices for line in lines])
tvertices = [ax.transData.transform(v) for v in vertices]
overlap = bbox.count_contains(tvertices) + bbox.count_overlaps(bboxes)
if get_vertices:
return overlap, vertices
else:
return overlap
示例13: hist_legend
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def hist_legend(ax=None, **kwargs):
from matplotlib.lines import Line2D
if ax is None:
ax = plt.gca()
handles, labels = ax.get_legend_handles_labels()
new_handles = [
Line2D([], [], c=h.get_edgecolor()) if type(h) == mpl.patches.Polygon else h
for h in handles
]
ax.legend(handles=new_handles[::-1], labels=labels[::-1], **kwargs)
return ax
示例14: _config_axes
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def _config_axes(self, X, Y):
'''
Make an axes patch and outline.
'''
ax = self.ax
ax.set_frame_on(False)
ax.set_navigate(False)
xy = self._outline(X, Y)
ax.update_datalim(xy)
ax.set_xlim(*ax.dataLim.intervalx)
ax.set_ylim(*ax.dataLim.intervaly)
if self.outline is not None:
self.outline.remove()
self.outline = lines.Line2D(
xy[:, 0], xy[:, 1], color=mpl.rcParams['axes.edgecolor'],
linewidth=mpl.rcParams['axes.linewidth'])
ax.add_artist(self.outline)
self.outline.set_clip_box(None)
self.outline.set_clip_path(None)
c = mpl.rcParams['axes.facecolor']
if self.patch is not None:
self.patch.remove()
self.patch = mpatches.Polygon(xy, edgecolor=c,
facecolor=c,
linewidth=0.01,
zorder=-1)
ax.add_artist(self.patch)
self.update_ticks()
示例15: create_artists
# 需要导入模块: from matplotlib import lines [as 别名]
# 或者: from matplotlib.lines import Line2D [as 别名]
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
legline = Line2D(xdata, ydata)
self.update_prop(legline, orig_handle, legend)
legline.set_drawstyle('default')
legline.set_marker("")
legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
self.update_prop(legline_marker, orig_handle, legend)
legline_marker.set_linestyle('None')
if legend.markerscale != 1:
newsz = legline_marker.get_markersize() * legend.markerscale
legline_marker.set_markersize(newsz)
# we don't want to add this to the return list because
# the texts and handles are assumed to be in one-to-one
# correspondence.
legline._legmarker = legline_marker
legline.set_transform(trans)
legline_marker.set_transform(trans)
return [legline, legline_marker]