def draw_legend(data, da, lyr):
"""
Draw a point in the box
Parameters
----------
data : dataframe
params : dict
lyr : layer
Returns
-------
out : DrawingArea
"""
key = mlines.Line2D([0.5*da.width],
[0.5*da.height],
alpha=data['alpha'],
marker='o',
markersize=da.width/2,
markerfacecolor=data['fill'],
markeredgecolor=data['color'])
da.add_artist(key)
return da
python类Line2D()的实例源码
def test_generate_plot_lines():
colordict = {
'cat1': '#001122',
'cat2': '#112233',
'cat3': '#223344',
}
styledict = {
'cat1': '-',
'cat2': '--',
'cat3': '-',
}
plot_lines = generate_plot_lines(colordict,
lambda x: 'Cat {}'.format(x),
styledict)
assert len(plot_lines) == 3
for line in plot_lines:
assert type(line) == mlines.Line2D
assert 'Cat ' in line._label
assert '-' in line._linestyle
if line._label == 'Cat 2':
assert line._linestyle == '--'
def create_time_line(self, axes, t, y, time_value, label):
"""
creates a vertical line in the diagram, reaching from the x-axis to the plot at a given time t
:param axes:
:param t:
:param y:
:param time_value:
:param label:
:returns new counter value
"""
# don't create lines on the very left
if time_value == t[-1]:
return
# create timeLine
time_line = Line2D([time_value, time_value],
[np.min(y), y[t.index(time_value)]],
ls=self.line_style,
c=self.line_color)
axes.add_line(time_line)
axes.text(time_value + self.spacing, self.label_posistions[self.label_counter], label, size=self.font_size)
def draw_legend(self, legend_ax):
# Make a legend with proxy artists
xpos_artist = lines.Line2D([],[], color='orange')
ypos_artist = lines.Line2D([],[], color='limegreen')
numpts_artist = lines.Line2D([],[], color='purple', linewidth=1)
frozen_artist = patches.Rectangle((0,0), 1, 1, fc='lightblue', ec='None')
missing_artist = patches.Rectangle((0,0), 1, 1, fc='yellow', ec='None')
lost_artist = patches.Rectangle((0,0), 1, 1, fc='red', ec='None')
# Place it in center of top "subplot" area
legend_ax.legend(
[xpos_artist, ypos_artist, numpts_artist,
frozen_artist, missing_artist, lost_artist],
['x-pos', 'y-pos', '# Detection pts',
'Frozen', 'Missing', 'Lost'],
loc='center',
fontsize=12,
ncol=4,
)
legend_ax.axis('off')
format_axis(legend_ax)
def create_dummy_line(**kwds):
return Line2D([], [], **kwds)
def draw_element(ax,el,**kwargs):
coords = np.array([nd.coord for nd in el.nodes])
line = Line2D(coords[:,0],coords[:,1],**kwargs)
line2 = Line2D((coords[:,0][-1],coords[:,0][0]),(coords[:,1][-1],coords[:,1][0]),**kwargs)
ax.add_line(line)
ax.add_line(line2)
def draw_element_disp(ax,el,factor = 1.,ls = "dashed",**kwargs):
coord = np.array([nd.coord for nd in el.nodes])
n = len(coord)
disp = np.array([nd.disp[key] for nd in el.nodes for key in ["Ux","Uy"]])
disp = disp.reshape(n,2)
new_coords = coord+disp*factor*1e3
line = Line2D(new_coords[:,0],new_coords[:,1],linestyle = ls,**kwargs)
line2 = Line2D((new_coords[:,0][-1],new_coords[:,0][0]),(new_coords[:,1][-1],new_coords[:,1][0]),ls = ls,**kwargs)
ax.add_line(line)
ax.add_line(line2)
def draw_legend(data, da, lyr):
"""
Draw a rectangle with a horizontal strike in the box
Parameters
----------
data : dataframe
da : DrawingArea
lyr : layer
Returns
-------
out : DrawingArea
"""
data['size'] *= SIZE_FACTOR
# background
facecolor = to_rgba(data['fill'], data['alpha'])
if facecolor is None:
facecolor = 'none'
bg = Rectangle((da.width*.125, da.height*.25),
width=da.width*.75,
height=da.height*.5,
linewidth=data['size'],
facecolor=facecolor,
edgecolor=data['color'],
linestyle=data['linetype'],
capstyle='projecting',
antialiased=False)
da.add_artist(bg)
strike = mlines.Line2D([da.width*.125, da.width*.875],
[da.height*.5, da.height*.5],
linestyle=data['linetype'],
linewidth=data['size'],
color=data['color'])
da.add_artist(strike)
return da
def draw_legend(data, da, lyr):
"""
Draw a vertical line in the box
Parameters
----------
data : dataframe
da : DrawingArea
lyr : layer
Returns
-------
out : DrawingArea
"""
x = [0.5 * da.width] * 2
y = [0, da.height]
data['size'] *= SIZE_FACTOR
key = mlines.Line2D(x,
y,
alpha=data['alpha'],
linestyle=data['linetype'],
linewidth=data['size'],
color=data['color'],
solid_capstyle='butt',
antialiased=False)
da.add_artist(key)
return da
def draw_legend(data, da, lyr):
"""
Draw a horizontal line in the box
Parameters
----------
data : dataframe
da : DrawingArea
lyr : layer
Returns
-------
out : DrawingArea
"""
data['size'] *= SIZE_FACTOR
x = [0, da.width]
y = [0.5 * da.height] * 2
key = mlines.Line2D(x,
y,
alpha=data['alpha'],
linestyle=data['linetype'],
linewidth=data['size'],
color=data['color'],
solid_capstyle='butt',
antialiased=False)
da.add_artist(key)
return da
def draw_legend(data, da, lyr):
"""
Draw a point in the box
Parameters
----------
data : dataframe
params : dict
lyr : layer
Returns
-------
out : DrawingArea
"""
if data['fill'] is None:
data['fill'] = data['color']
size = (data['size']+data['stroke'])*SIZE_FACTOR
stroke = data['stroke'] * SIZE_FACTOR
key = mlines.Line2D([0.5*da.width],
[0.5*da.height],
alpha=data['alpha'],
marker=data['shape'],
markersize=size,
markerfacecolor=data['fill'],
markeredgecolor=data['color'],
markeredgewidth=stroke)
da.add_artist(key)
return da
def generate_plot_lines(colordict, label_fcn, styledict):
plot_lines = []
# plot_labs = []
for cat_val in sorted(colordict.keys()):
# http://matplotlib.org/users/legend_guide.html
lin = mlines.Line2D(
xdata=[],
ydata=[],
linestyle=styledict[cat_val],
color=colordict[cat_val],
label=label_fcn(cat_val)
)
plot_lines.append(lin)
# plot_labs.append(mt)
return plot_lines
def fooCandlestick(ax, quotes, width=0.5, colorup='#FFA500', colordown='#222', alpha=1.0):
OFFSET = width/2.0
lines = []
boxes = []
for q in quotes:
timestamp, op, hi, lo, close = q[:5]
box_h = max(op, close)
box_l = min(op, close)
height = box_h - box_l
if close>=op:
color = '#3fd624'
else:
color = '#e83e2c'
vline_lo = Line2D( xdata=(timestamp, timestamp), ydata=(lo, box_l), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
vline_hi = Line2D( xdata=(timestamp, timestamp), ydata=(box_h, hi), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
rect = Rectangle( xy = (timestamp-OFFSET, box_l), width = width, height = height, facecolor = color, edgecolor = color, zorder=10)
rect.set_alpha(alpha)
lines.append(vline_lo)
lines.append(vline_hi)
boxes.append(rect)
ax.add_line(vline_lo)
ax.add_line(vline_hi)
ax.add_patch(rect)
ax.autoscale_view()
return lines, boxes
# Enable a Grid
def line2d(x, y, ax, **kwargs):
"""plot a 2d line between (x1, y1) and (x2, y2)"""
line = Line2D(x, y, linewidth=1, color='k', **kwargs)
ax.add_line(line)
def createTimeLine(self, axes, t, y, time_value, label):
if time_value != t[-1]:
# create timeLine
timeLine = Line2D([time_value, time_value], \
[axes.get_ylim()[0], y[t.index(time_value)]], \
ls=self.line_style, \
c=self.line_color)
axes.add_line(timeLine)
# create label
axes.text(time_value + self.spacing, self.posLabel[self.counter], label, size=self.font_size)
self.counter = self.counter + 1
def create_time_line(self, axes, t, y, time_value, label):
if time_value != t[-1]:
time_line = Line([time_value, time_value],
[np.min(y), y[np.where(t == time_value)][0]],
linewidth=self.line_width,
ls=self.line_style,
c=self.line_color)
axes.add_line(time_line)
axes.text(time_value + self.spacing,
self.label_positions[self.counter],
label,
color=self.font_color,
size=self.font_size)
self.counter += 1
def __init__(self, visuals):
self.visuals = visuals
if visuals:
self.train_loss_list = []
self.val_loss_list = []
self.val_kappa_list = []
self.val_accu_list = []
self.epoch_list = []
plt.ion()
self.f, self.ax = plt.subplots(3, 1)
red_line = mlines.Line2D([], [], color='red', markersize=15, label='Training loss')
green_line = mlines.Line2D([], [], color='green', markersize=15, label='Validation loss')
self.ax[0].legend(handles=[red_line, green_line], prop={'size': 8})
store_training_logs.delete_file('run_script_logs.pkl')
def __init__(self, visuals):
self.visuals = visuals
if visuals:
self.train_loss_list = []
self.val_loss_list = []
self.val_kappa_list = []
self.val_accu_list = []
self.epoch_list = []
plt.ion()
self.f, self.ax = plt.subplots(3, 1)
self.f.subplots_adjust(hspace=.7)
red_line = mlines.Line2D([], [], color='red', markersize=15, label='Training loss')
green_line = mlines.Line2D([], [], color='green', markersize=15, label='Validation loss')
self.ax[0].legend(handles=[red_line, green_line], prop={'size': 8})
store_training_logs.delete_file('run_script_logs.pkl')
def example_naivehierarchicalclustering():
"""Naive hierarchical clustering algorithm using DTW and based on .
For a more efficient approach, check:
Mueen, A and Keogh, E, Extracting Optimal Performance from Dynamic Time Warping,
Tutorial, KDD 2016
http://www.cs.unm.edu/~mueen/DTW.pdf
:return: None
"""
series = [
np.array([0.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0]),
np.array([0.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0]),
np.array([2.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]),
np.array([2.0, 1.0, 1.0, 0.0, 0.0, 2.0, 3.0]),
np.array([4.0, 2.0, 1.0, 0.0, 0.0, 1.0, 3.0])
]
dists = dtw.distance_matrix_fast(series)
print("Distance matrix:\n{}".format(dists))
dists_cond = np.zeros(size_cond(len(series)))
idx = 0
for r in range(len(series)-1):
dists_cond[idx:idx+len(series)-r-1] = dists[r, r+1:]
idx += len(series)-r-1
z = linkage(dists_cond, method='complete', metric='euclidean')
print(z)
fig, axes = plt.subplots(2, 1, figsize=(8, 3))
for idx, serie in enumerate(series):
serie += idx * 0.1
axes[0].plot(serie, label=str(idx))
axes[0].text(0 + 0.15 * (-1)**idx * idx, serie[0] + 0.15 * idx, idx)
axes[0].add_line(Line2D([0, 0 + 0.15 * (-1)**idx * idx], [serie[0], serie[0] + 0.15 * idx],
linewidth=1, color='gray'))
axes[0].legend(loc=1)
dendrogram(z, ax=axes[1])
plt.show(block=True)
flight_analysis_bin_heatmap.py 文件源码
项目:PIE_ISAE_Essais_Vol
作者: YuanxiangFranck
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def create_proxy(c):
line = Line2D([0],[0],color=c,marker='s',linestyle='None')
return line
flight_analysis_regul_heatmap.py 文件源码
项目:PIE_ISAE_Essais_Vol
作者: YuanxiangFranck
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
def create_proxy(c):
line = Line2D([0],[0],color=c,marker='s',linestyle='None')
return line
flight_analysis_regul_heatmap.py 文件源码
项目:PIE_ISAE_Essais_Vol
作者: YuanxiangFranck
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def create_proxy(c):
line = Line2D([0],[0],color=c,marker='s',linestyle='None')
return line
def add_mapping(patches, colors, start_ratio, patch_size, ind_bgn,
top_left_list, loc_diff_list, num_show_list, size_list):
start_loc = top_left_list[ind_bgn] \
+ (num_show_list[ind_bgn] - 1) * np.array(loc_diff_list[ind_bgn]) \
+ np.array([start_ratio[0] * size_list[ind_bgn],
-start_ratio[1] * size_list[ind_bgn]])
end_loc = top_left_list[ind_bgn + 1] \
+ (num_show_list[ind_bgn + 1] - 1) \
* np.array(loc_diff_list[ind_bgn + 1]) \
+ np.array([(start_ratio[0] + .5 * patch_size / size_list[ind_bgn]) *
size_list[ind_bgn + 1],
-(start_ratio[1] - .5 * patch_size / size_list[ind_bgn]) *
size_list[ind_bgn + 1]])
patches.append(Rectangle(start_loc, patch_size, patch_size))
colors.append(Dark)
patches.append(Line2D([start_loc[0], end_loc[0]],
[start_loc[1], end_loc[1]]))
colors.append(Black)
patches.append(Line2D([start_loc[0] + patch_size, end_loc[0]],
[start_loc[1], end_loc[1]]))
colors.append(Black)
patches.append(Line2D([start_loc[0], end_loc[0]],
[start_loc[1] + patch_size, end_loc[1]]))
colors.append(Black)
patches.append(Line2D([start_loc[0] + patch_size, end_loc[0]],
[start_loc[1] + patch_size, end_loc[1]]))
colors.append(Black)
def __init__(self,init,**kwargs):
lines.Line2D.__init__(self,[],[],**kwargs)
self.xdata = np.array([0,1/5.0,2/5.,3/5.,4/5.,1])+init
self.ydata = np.array([0,0,0.05,-0.05,0,0])
# Set data
self.set_xdata(self.xdata)
self.set_ydata(self.ydata)
#self.set_linestyle("-") #Solid line
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()
def drawgreatcircle(self,lon1,lat1,lon2,lat2,del_s=100.,**kwargs):
"""
Draw a great circle on the map from the longitude-latitude
pair ``lon1,lat1`` to ``lon2,lat2``
.. tabularcolumns:: |l|L|
============== =======================================================
Keyword Description
============== =======================================================
del_s points on great circle computed every del_s kilometers
(default 100).
\**kwargs other keyword arguments are passed on to :meth:`plot`
method of Basemap instance.
============== =======================================================
.. note::
Cannot handle situations in which the great circle intersects
the edge of the map projection domain, and then re-enters the domain.
Returns a matplotlib.lines.Line2D object.
"""
# use great circle formula for a perfect sphere.
gc = pyproj.Geod(a=self.rmajor,b=self.rminor)
az12,az21,dist = gc.inv(lon1,lat1,lon2,lat2)
npoints = int((dist+0.5*1000.*del_s)/(1000.*del_s))
lonlats = gc.npts(lon1,lat1,lon2,lat2,npoints)
lons = [lon1]; lats = [lat1]
for lon, lat in lonlats:
lons.append(lon)
lats.append(lat)
lons.append(lon2); lats.append(lat2)
x, y = self(lons, lats)
return self.plot(x,y,**kwargs)
def drawgreatcircle(self,lon1,lat1,lon2,lat2,del_s=100.,**kwargs):
"""
Draw a great circle on the map from the longitude-latitude
pair ``lon1,lat1`` to ``lon2,lat2``
.. tabularcolumns:: |l|L|
============== =======================================================
Keyword Description
============== =======================================================
del_s points on great circle computed every del_s kilometers
(default 100).
\**kwargs other keyword arguments are passed on to :meth:`plot`
method of Basemap instance.
============== =======================================================
.. note::
Cannot handle situations in which the great circle intersects
the edge of the map projection domain, and then re-enters the domain.
Returns a matplotlib.lines.Line2D object.
"""
# use great circle formula for a perfect sphere.
gc = pyproj.Geod(a=self.rmajor,b=self.rminor)
az12,az21,dist = gc.inv(lon1,lat1,lon2,lat2)
npoints = int((dist+0.5*1000.*del_s)/(1000.*del_s))
lonlats = gc.npts(lon1,lat1,lon2,lat2,npoints)
lons = [lon1]; lats = [lat1]
for lon, lat in lonlats:
lons.append(lon)
lats.append(lat)
lons.append(lon2); lats.append(lat2)
x, y = self(lons, lats)
return self.plot(x,y,**kwargs)
def factor_comparison(dfs, keys, figsize=(7,5)):
compare = lookup(dfs, show_totals=True,
keys=keys, exclude=['Solar', 'Wind']).fillna(0.)
n_fueltypes, n_countries = compare.shape
compare.columns.labels
c= [tech_colors2[i] for i in compare.index.values[:-1]] + ['gold']
rcParams["axes.prop_cycle"] = cycler(color=c)
#where both are zero,
compare[compare.groupby(level=0, axis=1).transform(np.sum)<0.5]=np.nan
fig, ax = plt.subplots(1,1, figsize=figsize)
compare.T.plot(ax=ax, markevery=(0,2),
style='o', markersize=5)
compare.T.plot(ax=ax, markevery=(1,2),
style='s', legend=None, markersize=4.5)
lgd = ax.get_legend_handles_labels()
for i,j in enumerate(compare.T.index.levels[0]):
ax.plot(np.array([0,1])+(2*i), compare.T.loc[j])
indexhandles = [Line2D([0.4,.6],[.4,.6], marker=m, linewidth=0.,
markersize=msize,
color='w', markeredgecolor='k', markeredgewidth=0.5)
for m, msize in [['o', 5.], ['s', 4.5]]]
indexlabels = ['Matched Dataset', 'ENTSOE Stats']
ax.add_artist(ax.legend(handles=indexhandles, labels=indexlabels))
ax.legend(handles= lgd[0][:len(c)], labels=lgd[1][:len(c)]
,title=False, loc=2)
ax.set_xlim(-1,n_countries)
ax.xaxis.grid(False)
ax.set_xticks(np.linspace(0.5,n_countries-1.5,n_countries/2))
ax.set_xticklabels(compare.columns.levels[0].values, rotation=90)
ax.set_xlabel('')
ax.set_ylabel('Capacity [GW]')
fig.tight_layout(pad=0.5)
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 add_reachable_poly(self, poly_verts, parent, mode_name):
'''add a polygon which was reachable'''
assert isinstance(parent, ContinuousPostParent)
if len(poly_verts) <= 2:
markers = self.parent_to_markers.get(parent)
if markers is None:
face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)
markers = Line2D([], [], animated=True, ls='None', alpha=0.5, marker='o', mew=2, ms=5,
mec=edge_col, mfc=face_col)
self.axes.add_line(markers)
self.parent_to_markers[parent] = markers
xdata = markers.get_xdata()
ydata = markers.get_ydata()
xdata.append(poly_verts[0][0])
ydata.append(poly_verts[0][1])
markers.set_xdata(xdata)
markers.set_ydata(ydata)
else:
polys = self.parent_to_polys.get(parent)
if polys is None:
face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)
polys = collections.PolyCollection([], lw=2, animated=True, alpha=0.5,
edgecolor=edge_col, facecolor=face_col)
self.axes.add_collection(polys)
self.parent_to_polys[parent] = polys
paths = polys.get_paths()
codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
paths.append(Path(poly_verts, codes))