def surface_plot(figure,X,Y,Z,color1,color2=None,xlabel="",ylabel="",zlabel="",alpha=1.0,linewidth=3,label=""):
from mpl_toolkits.mplot3d import axes3d
from matplotlib.colors import LinearSegmentedColormap
if color2 is None:
color2 = color1
cdict = {'red': ((0.0, color1[0], color1[0]),(1.0, color2[0], color2[0])),
'green': ((0.0, color1[1], color1[1]),(1.0, color2[1], color2[1])),
'blue': ((0.0, color1[2], color1[2]),(1.0, color2[2], color2[2]))}
cmap = LinearSegmentedColormap('CMap', cdict)
font = fm.FontProperties(family = 'Trebuchet', weight ='light')
figure.patch.set_facecolor('white')
axes = figure.add_subplot(111,projection='3d')
if X.ndim<2:
X = np.tile(np.array(X),(Y.shape[-1],1)).transpose()
if Y.ndim<2:
Y = np.tile(np.array(Y),(X.shape[0],1))
axes.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cmap,alpha=alpha,linewidth=linewidth,label=label)
axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
axes.set_xlim(X.min(),X.max())
axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
axes.set_ylim(Y.min(),Y.max())
axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
axes.set_zlabel(zlabel, fontproperties=font, size=10, style='italic')
axes.set_zlim(Z.min(),Z.max())
axes.set_zticklabels(axes.get_zticks(),fontproperties=font, size=12)
python类colors()的实例源码
def density_plot(figure,X,Y,color,xlabel="",ylabel="",n_points=10,linewidth=1,marker_size=40.,alpha=1.0,label=""):
font = fm.FontProperties(family = 'Trebuchet', weight ='light')
#font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
figure.patch.set_facecolor('white')
axes = figure.add_subplot(111)
# axes.plot(X,Y,linewidth=1,color=tuple(color2),alpha=0.2)
# ratios = (Y-Y.min())/(Y.max()-Y.min())
# X_min = X.mean()-3*X.std()
# X_max = X.mean()+3*X.std()
X_min = np.percentile(X,100/n_points)
X_max = np.percentile(X,100 - 100/n_points)
Y_min = np.percentile(Y,100/n_points)
# Y_min = Y.mean()-3*Y.std()
Y_max = np.percentile(Y,100 - 100/n_points)
X_grid = np.linspace(X_min,X_max,n_points)
Y_grid = np.linspace(Y_min,Y_max,n_points)
X_sampled = X_grid[vq(X,X_grid)[0]]
Y_sampled = Y_grid[vq(Y,Y_grid)[0]]
point_density = {}
for x in np.unique(X_sampled):
point_count = nd.sum(np.ones_like(np.where(X_sampled==x)),Y_sampled[np.where(X_sampled==x)],index=np.unique(Y_sampled))
for i,y in enumerate(np.unique(Y_sampled)):
point_density[(x,y)] = point_count[i]/len(Y)
point_area = np.array([np.pi*10.0*marker_size*point_density[(x,y)]/np.array(point_density.values()).max() for x,y in zip(X_sampled,Y_sampled)])
#colors = np.random.rand(len(X))
colors = np.array([point_density[(x,y)]/np.array(point_density.values()).max() * color for x,y in zip(X_sampled,Y_sampled)])
colors += np.array([(1-point_density[(x,y)]/np.array(point_density.values()).max()) * np.ones(3) for x,y in zip(X_sampled,Y_sampled)])
axes.scatter(X_sampled,Y_sampled,s=point_area,c=colors,linewidth=linewidth,alpha=alpha,label=label)
axes.set_xlim(X_min,X_max)
axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
axes.set_ylim(Y_min,Y_max)
axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def violin_plot(figure,X,data,colors,xlabel="",ylabel="",n_points=400,violin_width=None,linewidth=3,marker_size=20):
font = fm.FontProperties(family = 'Trebuchet', weight ='light')
#font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
figure.patch.set_facecolor('white')
axes = figure.add_subplot(111)
if violin_width is None:
if len(X)>1:
violin_width = ((np.array(X)[1:] - np.array(X)[:-1]).mean())/3.
else:
violin_width = 0.33
for x in xrange(len(X)):
color = colors[x]
Y = gaussian_kde(data[x])
D_smooth = np.linspace(np.percentile(Y.dataset,1),np.percentile(Y.dataset,99),n_points)
Y_smooth = Y.evaluate(D_smooth)
Y_smooth = violin_width*Y_smooth/Y_smooth.max()
axes.fill_betweenx(D_smooth,X[x],X[x]+Y_smooth,facecolor=color,alpha=0.1)
axes.fill_betweenx(D_smooth,X[x],X[x]-Y_smooth,facecolor=color,alpha=0.1)
axes.plot(X[x]+Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8)
axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8)
axes.plot([X[x]-Y_smooth[0],X[x]+Y_smooth[0]],[D_smooth[0],D_smooth[0]],color=color,linewidth=linewidth,alpha=0.8)
axes.plot([X[x]-Y_smooth[-1],X[x]+Y_smooth[-1]],[D_smooth[-1],D_smooth[-1]],color=color,linewidth=linewidth,alpha=0.8)
axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8)
axes.plot(X[x],np.percentile(data[x],50),'o',markersize=marker_size,markeredgewidth=linewidth,color=color)
axes.plot([X[x],X[x]],[np.percentile(data[x],25),np.percentile(data[x],75)],color=color,linewidth=2*linewidth,alpha=0.5)
axes.set_xlim(min(X)-1,max(X)+1)
axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
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)
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def _validate_color_args(self):
if 'color' not in self.kwds and 'colors' in self.kwds:
warnings.warn(("'colors' is being deprecated. Please use 'color'"
"instead of 'colors'"))
colors = self.kwds.pop('colors')
self.kwds['color'] = colors
if ('color' in self.kwds and self.nseries == 1):
# support series.plot(color='green')
self.kwds['color'] = [self.kwds['color']]
if ('color' in self.kwds or 'colors' in self.kwds) and \
self.colormap is not None:
warnings.warn("'color' and 'colormap' cannot be used "
"simultaneously. Using 'color'")
if 'color' in self.kwds and self.style is not None:
if com.is_list_like(self.style):
styles = self.style
else:
styles = [self.style]
# need only a single match
for s in styles:
if re.match('^[a-z]+?', s) is not None:
raise ValueError(
"Cannot pass 'style' string with a color "
"symbol and 'color' keyword argument. Please"
" use one or the other or pass 'style' "
"without a color symbol")
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def _make_plot(self):
if self._is_ts_plot():
from pandas.tseries.plotting import _maybe_convert_index
data = _maybe_convert_index(self._get_ax(0), self.data)
x = data.index # dummy, not used
plotf = self._ts_plot
it = self._iter_data(data=data, keep_index=True)
else:
x = self._get_xticks(convert_period=True)
plotf = self._plot
it = self._iter_data()
stacking_id = self._get_stacking_id()
is_errorbar = any(e is not None for e in self.errors.values())
colors = self._get_colors()
for i, (label, y) in enumerate(it):
ax = self._get_ax(i)
kwds = self.kwds.copy()
style, kwds = self._apply_style_colors(colors, kwds, i, label)
errors = self._get_errorbars(label=label, index=i)
kwds = dict(kwds, **errors)
label = com.pprint_thing(label) # .encode('utf-8')
kwds['label'] = label
newlines = plotf(ax, x, y, style=style, column_num=i,
stacking_id=stacking_id,
is_errorbar=is_errorbar,
**kwds)
self._add_legend_handle(newlines[0], label, index=i)
lines = _get_all_lines(ax)
left, right = _get_xlim(lines)
ax.set_xlim(left, right)
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def _validate_color_args(self):
if 'color' in self.kwds:
if self.colormap is not None:
warnings.warn("'color' and 'colormap' cannot be used "
"simultaneously. Using 'color'")
self.color = self.kwds.pop('color')
if isinstance(self.color, dict):
valid_keys = ['boxes', 'whiskers', 'medians', 'caps']
for key, values in compat.iteritems(self.color):
if key not in valid_keys:
raise ValueError("color dict contains invalid "
"key '{0}' "
"The key must be either {1}"
.format(key, valid_keys))
else:
self.color = None
# get standard colors for default
colors = _get_standard_colors(num_colors=3,
colormap=self.colormap,
color=None)
# use 2 colors by default, for box/whisker and median
# flier colors isn't needed here
# because it can be specified by ``sym`` kw
self._boxes_c = colors[0]
self._whiskers_c = colors[0]
self._medians_c = colors[2]
self._caps_c = 'k' # mpl default
def __init__(self, gt, joints, dolegend=True, linewidth=1):
"""
Initialize class
:type gt: groundtruth joints
:type joints: calculated joints
"""
super(ICVLHandposeEvaluation, self).__init__(gt, joints, dolegend, linewidth)
import matplotlib.colors
# setup specific stuff
self.jointNames = ['C', 'T1', 'T2', 'T3', 'I1', 'I2', 'I3', 'M1', 'M2', 'M3', 'R1', 'R2', 'R3', 'P1', 'P2', 'P3']
self.jointColors = [matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 0, 0.0]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.6]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.8]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 1.0]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.6]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.8]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 1.0]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.6]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.8]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 1.0]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.6]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.8]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 1.0]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.6]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.8]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 1.0]]]))[0, 0]]
self.jointConnections = [[0, 1], [1, 2], [2, 3], [0, 4], [4, 5], [5, 6], [0, 7], [7, 8], [8, 9], [0, 10],
[10, 11], [11, 12], [0, 13], [13, 14], [14, 15]]
self.jointConnectionColors = [matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.00, 1, 1]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.33, 1, 1]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.50, 1, 1]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.66, 1, 1]]]))[0, 0],
matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.6]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 0.8]]]))[0, 0], matplotlib.colors.hsv_to_rgb(numpy.asarray([[[0.83, 1, 1]]]))[0, 0]]
self.plotMaxJointDist = 80
self.VTKviewport = [0, 0, 180, 40, 40]
self.fps = 10.0
node_profile_analyzer_time_and_veh_legs.py 文件源码
项目:gtfspy
作者: CxAalto
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def _get_colors_for_boardings(cls, min_n_boardings, max_n_boardings):
cmap = NodeProfileAnalyzerTimeAndVehLegs.get_colormap_for_boardings(max_n_boardings)
colors = [cmap(float(n_boardings) / max_n_boardings) for n_boardings in range(int(max_n_boardings) + 1)]
return colors[min_n_boardings:max_n_boardings + 1]
node_profile_analyzer_time_and_veh_legs.py 文件源码
项目:gtfspy
作者: CxAalto
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def _multiply_color_saturation(cls, color, multiplier):
hsv = matplotlib.colors.rgb_to_hsv(color[:3])
rgb = matplotlib.colors.hsv_to_rgb((hsv[0], hsv[1] * multiplier, hsv[2]))
return list(iter(rgb)) + [1]
node_profile_analyzer_time_and_veh_legs.py 文件源码
项目:gtfspy
作者: CxAalto
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def _multiply_color_brightness(cls, color, multiplier):
hsv = matplotlib.colors.rgb_to_hsv(color[:3])
rgb = matplotlib.colors.hsv_to_rgb((hsv[0], hsv[1], max(0, min(1, hsv[2] * multiplier))))
return list(iter(rgb)) + [1]
def get_line_color(ix, modifier=None):
colour = _lines_colour_cycle[ix]
if modifier=='dark':
return tuple(c/2 for c in colors.hex2color(colour))
elif modifier=='light':
return tuple(1-(1-c)/2 for c in colors.hex2color(colour))
elif modifier is not None:
raise NotImplementedError(modifier)
return colors.hex2color(colour)
def set_cmap_synthetic(self, cmap):
self._cmap = pylab.get_cmap(cmap)
self._cNorm = colors.Normalize(vmin=0, vmax=self.nb_cells)
self._scalarMap_synthetic = pylab.cm.ScalarMappable(norm=self._cNorm, cmap=self._cmap)
def set_cmap_circus(self, cmap):
self._cmap = pylab.get_cmap(cmap)
self._cNorm = colors.Normalize(vmin=0, vmax=self.nb_templates)
self._scalarMap_circus = pylab.cm.ScalarMappable(norm=self._cNorm, cmap=self._cmap)
def diverge_map(low=(239/255., 65/255., 50/255.),
high=(39/255., 184/255., 148/255.)):
"""Low and high are colors that will be used for the two
ends of the spectrum. they can be either color strings
or rgb color tuples
"""
c = mcolors.ColorConverter().to_rgb
if isinstance(low, basestring): low = c(low)
if isinstance(high, basestring): high = c(high)
return make_colormap([low, c('white'), 0.5, c('white'), high])
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
g = nx.from_numpy_matrix(am)
if position is None:
position=nx.drawing.circular_layout(g)
fig = plt.figure()
if cls is None:
cls='r'
else:
# Make a user-defined colormap.
cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])
# Make a normalizer that will map the time values from
# [start_time,end_time+1] -> [0,1].
cnorm = mcol.Normalize(vmin=0, vmax=1)
# Turn these into an object that can be used to map time values to colors and
# can be passed to plt.colorbar().
cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
cpick.set_array([])
cls = cpick.to_rgba(cls)
plt.colorbar(cpick, ax=fig.add_subplot(111))
nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))
fig.savefig(os.path.join(self.plotdir, fig_name))
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
def plot_all_epochs(gen_data, I_XT_array, I_TY_array, axes, epochsInds, f, index_i, index_j, size_ind,
font_size, y_ticks, x_ticks, colorbar_axis, title_str, axis_font, bar_font, save_name, plot_error = True,index_to_emphasis=1000):
"""Plot the infomration plane with the epochs in diffrnet colors """
#If we want to plot the train and test error
if plot_error:
fig_strs = ['train_error','test_error','loss_train','loss_test' ]
fig_data = [np.squeeze(gen_data[fig_str]) for fig_str in fig_strs]
f1 = plt.figure(figsize=(12, 8))
ax1 = f1.add_subplot(111)
mean_sample = False if len(fig_data[0].shape)==1 else True
if mean_sample:
fig_data = [ np.mean(fig_data_s, axis=0) for fig_data_s in fig_data]
for i in range(len(fig_data)):
ax1.plot(epochsInds, fig_data[i],':', linewidth = 3 , label = fig_strs[i])
ax1.legend(loc='best')
f = plt.figure(figsize=(12, 8))
axes = f.add_subplot(111)
axes = np.array([[axes]])
I_XT_array = np.squeeze(I_XT_array)
I_TY_array = np.squeeze(I_TY_array)
if len(I_TY_array[0].shape) >1:
I_XT_array = np.mean(I_XT_array, axis=0)
I_TY_array = np.mean(I_TY_array, axis=0)
max_index = size_ind if size_ind != -1 else I_XT_array.shape[0]
cmap = plt.get_cmap('gnuplot')
#For each epoch we have diffrenet color
colors = [cmap(i) for i in np.linspace(0, 1, epochsInds[max_index-1]+1)]
#Change this if we have more then one network arch
nums_arc= -1
#Go over all the epochs and plot then with the right color
for index_in_range in range(0, max_index):
XT = I_XT_array[index_in_range, :]
TY = I_TY_array[index_in_range, :]
#If this is the index that we want to emphsis
if epochsInds[index_in_range] ==index_to_emphasis:
axes[index_i, index_j].plot(XT, TY, marker='o', linestyle=None, markersize=19, markeredgewidth=0.04,
linewidth=2.1,
color='g',zorder=10)
else:
axes[index_i, index_j].plot(XT[:], TY[:], marker='o', linestyle='-', markersize=12, markeredgewidth=0.01, linewidth=0.2,
color=colors[int(epochsInds[index_in_range])])
utils.adjustAxes(axes[index_i, index_j], axis_font=axis_font, title_str=title_str, x_ticks=x_ticks,
y_ticks=y_ticks, x_lim=[0, 25.1], y_lim=None,
set_xlabel=index_i == axes.shape[0] - 1, set_ylabel=index_j == 0, x_label='$I(X;T)$',
y_label='$I(T;Y)$', set_xlim=False,
set_ylim=False, set_ticks=True, label_size=font_size)
#Save the figure and add color bar
if index_i ==axes.shape[0]-1 and index_j ==axes.shape[1]-1:
utils.create_color_bar(f, cmap, colorbar_axis, bar_font, epochsInds, title='Epochs')
f.savefig(save_name+'.jpg', dpi=500, format='jpg')
def __init__(self, gt, joints, dolegend=True, linewidth=1):
"""
Initialize class
:type gt: groundtruth joints
:type joints: calculated joints
"""
if not (isinstance(gt, numpy.ndarray) or isinstance(gt, list)) or not (
isinstance(joints, list) or isinstance(joints, numpy.ndarray)):
raise ValueError("Params must be list or ndarray")
if len(gt) != len(joints):
print("Error: groundtruth has {} elements, eval data has {}".format(len(gt), len(joints)))
raise ValueError("Params must be the same size")
if len(gt) == len(joints) == 0:
print("Error: groundtruth has {} elements, eval data has {}".format(len(gt), len(joints)))
raise ValueError("Params must be of non-zero size")
if gt[0].shape != joints[0].shape:
print("Error: groundtruth has {} dims, eval data has {}".format(gt[0].shape, joints[0].shape))
raise ValueError("Params must be of same dimensionality")
self.gt = numpy.asarray(gt)
self.joints = numpy.asarray(joints)
assert (self.gt.shape == self.joints.shape)
self.colors = ['blue', 'green', 'red', 'cyan', 'magenta', 'black', 'brown', 'gray', 'indigo', 'pink',
'lightgreen', 'darkorange', 'peru', 'steelblue', 'turquoise']
self.linestyles = ['-'] # , '--', '-.', ':', '-', '--', '-.', ':']
self.linewidth = linewidth
self.dolegend = dolegend
self.subfolder = './eval/'
self.visiblemask = numpy.ones((self.gt.shape[0], self.gt.shape[1], 3))
self.jointNames = None
self.jointConnections = []
self.jointConnectionColors = []
self.plotMaxJointDist = 80
self.plotMeanJointDist = 80
self.plotMedianJointDist = 80
self.VTKviewport = [0, 0, 0, 0, 0]
def plotFramesWithinMax(self, basename, methodName='Our method', baseline=None):
"""
plot and save plot for fraction of frames within max distance
:param basename: file basename
:param methodName: our method name
:param baseline: list of baselines as tuple (Name,evaluation object)
:return: None
"""
if baseline is not None:
for bs in baseline:
if not (isinstance(bs[1], self.__class__)):
raise TypeError('baseline must be of type {} but {} provided'.format(self.__class__.__name__,
bs[1].__class__.__name__))
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([self.getNumFramesWithinMaxDist(j) / float(self.joints.shape[0]) * 100. for j in
range(0, self.plotMaxJointDist)], label=methodName, c=self.colors[0], linestyle=self.linestyles[0],
linewidth=self.linewidth)
bs_idx = 1
if baseline is not None:
for bs in baseline:
ax.plot([bs[1].getNumFramesWithinMaxDist(j) / float(self.joints.shape[0]) * 100. for j in
range(0, self.plotMaxJointDist)], label=bs[0], c=self.colors[bs_idx % len(self.colors)],
linestyle=self.linestyles[bs_idx % len(self.linestyles)], linewidth=self.linewidth)
bs_idx += 1
plt.xlabel('Distance threshold / mm')
plt.ylabel('Fraction of frames within distance / %')
plt.ylim([0.0, 100.0])
ax.grid(True)
if self.dolegend:
# Put a legend below current axis
handles, labels = ax.get_legend_handles_labels()
# lgd = ax.legend(handles, labels, loc='lower right', ncol=1) #, bbox_to_anchor=(0.5,-0.1)
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=3) # ncol=2, prop={'size': 14})
bbea = (lgd,)
else:
bbea = None
plt.show(block=False)
fig.savefig('{}/{}_frameswithin.pdf'.format(self.subfolder, basename), bbox_extra_artists=bbea,
bbox_inches='tight')
plt.close(fig)