def plot_img(image, gt_box):
""" Takes an image and bounding box coordinates and displays it using matplotlib """
# First print out image metrics
print("Using First Image of the Batch..")
print("Image Max Value (should be less than 1): %f" % image.max())
print("Image Min Value (should be greater than -1): %f" % image.min())
print("Image Mean Value (should be equal to 0): %f" % image.mean())
print("Digit: %d" % gt_box[4])
# Import matplotlib and setup axes
import matplotlib
matplotlib.use('TkAgg') # For Mac OS
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots(1)
# Plot Image First
ax.imshow(np.squeeze(image), cmap="gray")
# Calculate Bounding Box Rectangle and plot it
width = gt_box[3] - gt_box[1]
height = gt_box[2] - gt_box[0]
rect = patches.Rectangle((gt_box[1], gt_box[0]), height, width, linewidth=2, edgecolor='r', facecolor='none')
ax.add_patch(rect)
# Display Final composite image
plt.show()
python类patches()的实例源码
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
# https://matplotlib.org/examples/color/colormaps_reference.html
patches = []
for pos in var:
if shape == 'c':
patches.append(mpatches.Circle(pos, r))
elif shape == 'r':
patches.append(mpatches.RegularPolygon(pos, 4, r))
elif shape == 's':
patches.append(mpatches.RegularPolygon(pos, 6, r))
colors = np.linspace(start_color, .9, len(patches))
collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
collection.set_array(np.array(colors))
collection.set_clim(0, 1)
return collection
def sumCylinderCharges(xc, zc, r, qSecondary):
chargeRegionVerts = getCylinderPoints(xc, zc, r+0.5)
codes = chargeRegionVerts.shape[0]*[Path.LINETO]
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY
chargeRegionPath = Path(chargeRegionVerts, codes)
CCLocs = mesh.gridCC
chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs))
plateChargeLocs = CCLocs[chargeRegionInsideInd]
plateCharge = qSecondary[chargeRegionInsideInd]
posInd = np.where(plateCharge >= 0)
negInd = np.where(plateCharge < 0)
qPos = Utils.mkvc(plateCharge[posInd])
qNeg = Utils.mkvc(plateCharge[negInd])
qPosLoc = plateChargeLocs[posInd,:][0]
qNegLoc = plateChargeLocs[negInd,:][0]
qPosData = np.vstack([qPosLoc[:,0], qPosLoc[:,1], qPos]).T
qNegData = np.vstack([qNegLoc[:,0], qNegLoc[:,1], qNeg]).T
if qNeg.shape == (0,) or qPos.shape == (0,):
qNegAvgLoc = np.r_[-10, -10]
qPosAvgLoc = np.r_[+10, -10]
else:
qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg)
qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos)
qPosSum = np.sum(qPos)
qNegSum = np.sum(qNeg)
# # Check things by plotting
# fig = plt.figure()
# ax = fig.add_subplot(111)
# platePatch = patches.PathPatch(platePath, facecolor='none', lw=2)
# ax.add_patch(platePatch)
# chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2)
# ax.add_patch(chargeRegionPatch)
# plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b')
# plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r')
# ax.set_xlim(-15,5)
# ax.set_ylim(-25,-5)
# plt.axes().set_aspect('equal')
# plt.show()
return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc
# The only thing we need to make it work is a 2.5D field object in SimPEG
def sumCylinderCharges(xc, zc, r, qSecondary):
chargeRegionVerts = getCylinderPoints(xc, zc, r+0.5)
codes = chargeRegionVerts.shape[0]*[Path.LINETO]
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY
chargeRegionPath = Path(chargeRegionVerts, codes)
CCLocs = mesh.gridCC
chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs))
plateChargeLocs = CCLocs[chargeRegionInsideInd]
plateCharge = qSecondary[chargeRegionInsideInd]
posInd = np.where(plateCharge >= 0)
negInd = np.where(plateCharge < 0)
qPos = Utils.mkvc(plateCharge[posInd])
qNeg = Utils.mkvc(plateCharge[negInd])
qPosLoc = plateChargeLocs[posInd,:][0]
qNegLoc = plateChargeLocs[negInd,:][0]
qPosData = np.vstack([qPosLoc[:,0], qPosLoc[:,1], qPos]).T
qNegData = np.vstack([qNegLoc[:,0], qNegLoc[:,1], qNeg]).T
if qNeg.shape == (0,) or qPos.shape == (0,):
qNegAvgLoc = np.r_[-10, -10]
qPosAvgLoc = np.r_[+10, -10]
else:
qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg)
qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos)
qPosSum = np.sum(qPos)
qNegSum = np.sum(qNeg)
# # Check things by plotting
# fig = plt.figure()
# ax = fig.add_subplot(111)
# platePatch = patches.PathPatch(platePath, facecolor='none', lw=2)
# ax.add_patch(platePatch)
# chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2)
# ax.add_patch(chargeRegionPatch)
# plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b')
# plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r')
# ax.set_xlim(-15,5)
# ax.set_ylim(-25,-5)
# plt.axes().set_aspect('equal')
# plt.show()
return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc
def _plot_trading(self):
price_x = list(range(len(self.price[:self.step_st+self.obs_len])))
self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.68, 0.95, 0.9),zorder=1)
# maybe seperate up down color
#self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.75, 0.95, 0.9),zorder=1)
self.features_plot = [self.ax3.plot(price_x, self.obs_features[:self.step_st+self.obs_len, i],
c=self.features_color[i])[0] for i in range(self.feature_len)]
rect_high = self.obs_price.max() - self.obs_price.min()
self.target_box = self.ax.add_patch(
patches.Rectangle(
(self.step_st, self.obs_price.min()), self.obs_len, rect_high,
label='observation',edgecolor=(0.9, 1, 0.2, 0.8),facecolor=(0.95,1,0.1,0.3),
linestyle='-',linewidth=1.5,
fill=True)
) # remove background)
self.fluc_reward_plot_p = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]>=0,
facecolor=(1, 0.8, 0, 0.2), edgecolor=(1, 0.8, 0, 0.9), linewidth=0.8)
self.fluc_reward_plot_n = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]<=0,
facecolor=(0, 1, 0.8, 0.2), edgecolor=(0, 1, 0.8, 0.9), linewidth=0.8)
self.posi_plot_long = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len],
where=self.posi_arr[:self.step_st+self.obs_len]>=0,
facecolor=(1, 0.5, 0, 0.2), edgecolor=(1, 0.5, 0, 0.9), linewidth=1)
self.posi_plot_short = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len],
where=self.posi_arr[:self.step_st+self.obs_len]<=0,
facecolor=(0, 0.5, 1, 0.2), edgecolor=(0, 0.5, 1, 0.9), linewidth=1)
self.reward_plot_p = self.ax2.fill_between(price_x, 0,
self.reward_arr[:self.step_st+self.obs_len].cumsum(),
where=self.reward_arr[:self.step_st+self.obs_len].cumsum()>=0,
facecolor=(1, 0, 0, 0.2), edgecolor=(1, 0, 0, 0.9), linewidth=1)
self.reward_plot_n = self.ax2.fill_between(price_x, 0,
self.reward_arr[:self.step_st+self.obs_len].cumsum(),
where=self.reward_arr[:self.step_st+self.obs_len].cumsum()<=0,
facecolor=(0, 1, 0, 0.2), edgecolor=(0, 1, 0, 0.9), linewidth=1)
trade_x = self.posi_variation_arr.nonzero()[0]
trade_x_buy = [i for i in trade_x if self.posi_variation_arr[i]>0]
trade_x_sell = [i for i in trade_x if self.posi_variation_arr[i]<0]
trade_y_buy = [self.price[i] for i in trade_x_buy]
trade_y_sell = [self.price[i] for i in trade_x_sell]
trade_color_buy = [self._gen_trade_color(i) for i in trade_x_buy]
trade_color_sell = [self._gen_trade_color(i) for i in trade_x_sell]
self.trade_plot_buy = self.ax.scatter(x=trade_x_buy, y=trade_y_buy, s=100, marker='^',
c=trade_color_buy, edgecolors=(1,0,0,0.9), zorder=2)
self.trade_plot_sell = self.ax.scatter(x=trade_x_sell, y=trade_y_sell, s=100, marker='v',
c=trade_color_sell, edgecolors=(0,1,0,0.9), zorder=2)
def _plot_trading(self):
price_x = list(range(len(self.price[:self.step_st+self.obs_len])))
self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.68, 0.95, 0.9),zorder=1)
# maybe seperate up down color
#self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.75, 0.95, 0.9),zorder=1)
self.features_plot = [self.ax3.plot(price_x, self.obs_features[:self.step_st+self.obs_len, i],
c=self.features_color[i])[0] for i in range(self.feature_len)]
rect_high = self.obs_price.max() - self.obs_price.min()
self.target_box = self.ax.add_patch(
patches.Rectangle(
(self.step_st, self.obs_price.min()), self.obs_len, rect_high,
label='observation',edgecolor=(0.9, 1, 0.2, 0.8),facecolor=(0.95,1,0.1,0.3),
linestyle='-',linewidth=1.5,
fill=True)
) # remove background)
self.fluc_reward_plot_p = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]>=0,
facecolor=(1, 0.8, 0, 0.2), edgecolor=(1, 0.8, 0, 0.9), linewidth=0.8)
self.fluc_reward_plot_n = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]<=0,
facecolor=(0, 1, 0.8, 0.2), edgecolor=(0, 1, 0.8, 0.9), linewidth=0.8)
self.posi_plot_long = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len],
where=self.posi_arr[:self.step_st+self.obs_len]>=0,
facecolor=(1, 0.5, 0, 0.2), edgecolor=(1, 0.5, 0, 0.9), linewidth=1)
self.posi_plot_short = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len],
where=self.posi_arr[:self.step_st+self.obs_len]<=0,
facecolor=(0, 0.5, 1, 0.2), edgecolor=(0, 0.5, 1, 0.9), linewidth=1)
self.reward_plot_p = self.ax2.fill_between(price_x, 0,
self.reward_arr[:self.step_st+self.obs_len].cumsum(),
where=self.reward_arr[:self.step_st+self.obs_len].cumsum()>=0,
facecolor=(1, 0, 0, 0.2), edgecolor=(1, 0, 0, 0.9), linewidth=1)
self.reward_plot_n = self.ax2.fill_between(price_x, 0,
self.reward_arr[:self.step_st+self.obs_len].cumsum(),
where=self.reward_arr[:self.step_st+self.obs_len].cumsum()<=0,
facecolor=(0, 1, 0, 0.2), edgecolor=(0, 1, 0, 0.9), linewidth=1)
trade_x = self.posi_variation_arr.nonzero()[0]
trade_x_buy = [i for i in trade_x if self.posi_variation_arr[i]>0]
trade_x_sell = [i for i in trade_x if self.posi_variation_arr[i]<0]
trade_y_buy = [self.price[i] for i in trade_x_buy]
trade_y_sell = [self.price[i] for i in trade_x_sell]
trade_color_buy = [self._gen_trade_color(i) for i in trade_x_buy]
trade_color_sell = [self._gen_trade_color(i) for i in trade_x_sell]
self.trade_plot_buy = self.ax.scatter(x=trade_x_buy, y=trade_y_buy, s=100, marker='^',
c=trade_color_buy, edgecolors=(1,0,0,0.9), zorder=2)
self.trade_plot_sell = self.ax.scatter(x=trade_x_sell, y=trade_y_sell, s=100, marker='v',
c=trade_color_sell, edgecolors=(0,1,0,0.9), zorder=2)
def porestreamlines(polygon=None, rx=10., ry=10., Nx=100, Ny=100,
maxvalue=None, **fields):
"streamlines plot of vector field around nanopore"
# interpolate on regular mesh symmetric w.r.t. center axis
mesh2D = nanopores.RectangleMesh([-rx-0.1,-ry-0.1], [rx+0.1,ry+0.1], Nx, Ny)
fields2 = nanopores.convert2D(mesh2D, *(fields.values()))
# prepare polygon and copy to left half
settings = dict(closed=True, facecolor="#eeeeee", linewidth=3.,
edgecolor="black")
if polygon is not None:
polygon = np.array(polygon)
polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
# prepare plots
Ny += 1
Nx += 1
Y, X = np.mgrid[-ry:ry:Ny*1j, -rx:rx:Nx*1j]
U = np.zeros((Ny,Nx))
V = np.zeros((Ny,Nx))
formt = matplotlib.ticker.FuncFormatter(fmt)
ticks = [0] + [10**n for n in range(-16, -9)]
# determine uniform color range from fields (maybe round to nearest 10-power)
if maxvalue is None:
maxvalue = max(dolfin.norm(F.vector(), "linf") for F in fields2)
#maxvalue = 10**int(np.log10(maxvalue))
for i, F in enumerate(fields2):
Fstr = fields.keys()[i]
fig, ax = plt.subplots(figsize=(5, 4.5), num=Fstr)
# fill array with function values
for y in range(Ny):
for x in range(Nx):
f = F(X[y][x], Y[y][x])
U[y][x] = f[0]
V[y][x] = f[1]
# streamplot with logarithmic scale
strength = np.sqrt(U*U+V*V)
norm = matplotlib.colors.SymLogNorm(linthresh=ticks[1], linscale=1.0,
vmin=0., vmax=maxvalue)
strm = plt.streamplot(X, Y, U, V, arrowsize=1.5, linewidth=1.5, density=1.5,
cmap=cm.viridis, color=strength, norm=norm)
plt.colorbar(strm.lines, ticks=ticks, format=formt)
plt.xlabel('x [nm]') #, fontsize=20)
plt.ylabel('z [nm]') #, fontsize=20)
# plot pore polygon on top
if polygon is not None:
patch = patches.Polygon(polygon, **settings)
patchm = patches.Polygon(polygon_m, **settings)
patch.set_zorder(10)
patchm.set_zorder(10)
ax.add_patch(patch)
ax.add_patch(patchm)
def plot_input(fname, x, y_gt, s_gt, max_items_per_row=9):
"""Plot input, transformed input and output groundtruth sequence.
"""
num_ex = y_gt.shape[0]
num_items = y_gt.shape[1]
num_row, num_col, calc = calc_row_col(
num_ex, num_items, max_items_per_row=max_items_per_row)
f1, axarr = plt.subplots(num_row, num_col, figsize=(20, num_row))
set_axis_off(axarr, num_row, num_col)
cmap = ['r', 'y', 'c', 'g', 'm']
for ii in xrange(num_ex):
_x = x[ii]
_x = _x[:, :, [2, 1, 0]]
# _x = x[ii, :, :, [2, 1, 0]]
for jj in xrange(num_items):
row, col = calc(ii, jj)
axarr[row, col].imshow(_x)
nz = y_gt[ii, jj].nonzero()
if nz[0].size > 0:
top_left_x = nz[1].min()
top_left_y = nz[0].min()
bot_right_x = nz[1].max() + 1
bot_right_y = nz[0].max() + 1
axarr[row, col].add_patch(
patches.Rectangle(
(top_left_x, top_left_y),
bot_right_x - top_left_x,
bot_right_y - top_left_y,
fill=False,
color=cmap[jj % len(cmap)]))
axarr[row, col].add_patch(
patches.Rectangle(
(top_left_x, top_left_y - 25),
25,
25,
fill=True,
color=cmap[jj % len(cmap)]))
axarr[row, col].text(
top_left_x + 5, top_left_y - 5, '{}'.format(jj), size=5)
plt.tight_layout(pad=2.0, w_pad=0.0, h_pad=0.0)
plt.savefig(fname, dpi=150)
plt.close('all')
pass
def visualize_traj_dynamic(ws_model, X, U, goal, time = None, name=None):
figure = pyplot.figure()
ax = figure.add_subplot(1,1,1)
cmap = get_cmap(len(X))
# plot obstacles
for hole in ws_model['circular_obstacles']:
srec = matplotlib.patches.Rectangle(
(hole[0]-hole[2], hole[1]-hole[2]),
2*hole[2], 2*hole[2],
facecolor= 'red',
fill = True,
alpha=1)
ax.add_patch(srec)
# ---plot traj---
for i in range(0,len(X)):
#-------plot car
robot = matplotlib.patches.Circle(
(X[i][0],X[i][1]),
radius = ws_model['robot_radius'],
facecolor=cmap(i),
edgecolor='black',
linewidth=1.0,
ls='solid',
alpha=1,
zorder=2)
ax.add_patch(robot)
#----------plot velocity
ax.arrow(X[i][0], X[i][1], U[i][0], U[i][1], head_width=0.05, head_length=0.1, fc=cmap(i), ec=cmap(i))
ax.text(X[i][0]-0.1, X[i][1]-0.1, r'$%s$' %i, fontsize=15, fontweight = 'bold',zorder=3)
ax.plot([goal[i][0]], [goal[i][1]], '*', color=cmap(i), markersize =15,linewidth=3.0)
if time:
ax.text(2,5.5,'$t=%.1f s$' %time,
fontsize=20, fontweight ='bold')
# ---set axes ---
ax.set_aspect('equal')
ax.set_xlim(-1.0, 6.0)
ax.set_ylim(-1.0, 6.0)
ax.set_xlabel(r'$x (m)$')
ax.set_ylabel(r'$y (m)$')
ax.grid('on')
if name:
pyplot.savefig(name, dpi = 200)
#pyplot.savefig(name,bbox_inches='tight')
pyplot.cla()
pyplot.close(figure)
return figure
def main():
# matplotlib.use('qt5agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
init_model()
MAT_DIR = './mat/test'
LABEL_DIR = './label/test'
for dirpath, dirnames, filenames in os.walk(MAT_DIR):
print(dirpath)
for filename in filenames:
if filename == 'full.mat':
data = sio.loadmat(os.path.join(dirpath, filename))
img = data['data']
centers = detection(img)
img_id = dirpath.split('/')[-1]
label_file = os.path.join(LABEL_DIR, img_id + '.mat')
labels = sio.loadmat(label_file)['label']
distance = (lambda x1, y1, x2, y2: abs(x1 - x2) + abs(y1 - y2))
centers = cluster(centers)
TP = 0
for x, y in labels:
for x_, y_ in centers:
if distance(x, y, x_, y_) < 36:
TP += 1
break
precision = float(TP) / len(centers)
recall = float(TP) / len(labels)
f_score = 2 * (precision * recall) / (precision + recall)
six.print_(precision, recall, f_score)
f = open(dirpath.split('/')[-1] + '-predict.txt', 'w')
for x, y in centers:
f.write(str(x) + ' ' + str(y) + '\n')
f.close()
f = open(dirpath.split('/')[-1] + '-label.txt', 'w')
for x, y in labels:
f.write(str(x) + ' ' + str(y) + '\n')
f.close()
# img = img / np.float32(256)
# plt.imshow(img, cmap=plt.cm.gray)
# currentAxis = plt.gca()
# for x, y in labels:
# currentAxis.add_patch(Rectangle((y - 90, x - 90),
# 180, 180, fill=None,
# alpha=1, color='blue'))
# for x, y in centers:
# currentAxis.add_patch(Rectangle((y - 90, x - 90),
# 180, 180, fill=None,
# alpha=1, color='red'))
# plt.show()
test_graphics_others.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def test_hist_df_legacy(self):
from matplotlib.patches import Rectangle
_check_plot_works(self.hist_df.hist)
# make sure layout is handled
df = DataFrame(randn(100, 3))
axes = _check_plot_works(df.hist, grid=False)
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
self.assertFalse(axes[1, 1].get_visible())
df = DataFrame(randn(100, 1))
_check_plot_works(df.hist)
# make sure layout is handled
df = DataFrame(randn(100, 6))
axes = _check_plot_works(df.hist, layout=(4, 2))
self._check_axes_shape(axes, axes_num=6, layout=(4, 2))
# make sure sharex, sharey is handled
_check_plot_works(df.hist, sharex=True, sharey=True)
# handle figsize arg
_check_plot_works(df.hist, figsize=(8, 10))
# check bins argument
_check_plot_works(df.hist, bins=5)
# make sure xlabelsize and xrot are handled
ser = df[0]
xf, yf = 20, 18
xrot, yrot = 30, 40
axes = ser.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot,
ylabelsize=yf, yrot=yrot)
xf, yf = 20, 18
xrot, yrot = 30, 40
axes = df.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot,
ylabelsize=yf, yrot=yrot)
tm.close()
# make sure kwargs to hist are handled
ax = ser.hist(normed=True, cumulative=True, bins=4)
# height of last bin (index 5) must be 1.0
rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
self.assertAlmostEqual(rects[-1].get_height(), 1.0)
tm.close()
ax = ser.hist(log=True)
# scale of y must be 'log'
self._check_ax_scales(ax, yaxis='log')
tm.close()
# propagate attr exception from matplotlib.Axes.hist
with tm.assertRaises(AttributeError):
ser.hist(foo='bar')
test_graphics_others.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def test_grouped_hist_legacy(self):
from matplotlib.patches import Rectangle
df = DataFrame(randn(500, 2), columns=['A', 'B'])
df['C'] = np.random.randint(0, 4, 500)
df['D'] = ['X'] * 500
axes = plotting.grouped_hist(df.A, by=df.C)
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
tm.close()
axes = df.hist(by=df.C)
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
tm.close()
# group by a key with single value
axes = df.hist(by='D', rot=30)
self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
self._check_ticks_props(axes, xrot=30)
tm.close()
# make sure kwargs to hist are handled
xf, yf = 20, 18
xrot, yrot = 30, 40
axes = plotting.grouped_hist(df.A, by=df.C, normed=True,
cumulative=True, bins=4,
xlabelsize=xf, xrot=xrot,
ylabelsize=yf, yrot=yrot)
# height of last bin (index 5) must be 1.0
for ax in axes.ravel():
rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
height = rects[-1].get_height()
self.assertAlmostEqual(height, 1.0)
self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot,
ylabelsize=yf, yrot=yrot)
tm.close()
axes = plotting.grouped_hist(df.A, by=df.C, log=True)
# scale of y must be 'log'
self._check_ax_scales(axes, yaxis='log')
tm.close()
# propagate attr exception from matplotlib.Axes.hist
with tm.assertRaises(AttributeError):
plotting.grouped_hist(df.A, by=df.C, foo='bar')
with tm.assert_produces_warning(FutureWarning):
df.hist(by='C', figsize='default')
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def _make_plot(self):
colors = self._get_colors(
num_colors=len(self.data), color_kwds='colors')
self.kwds.setdefault('colors', colors)
for i, (label, y) in enumerate(self._iter_data()):
ax = self._get_ax(i)
if label is not None:
label = com.pprint_thing(label)
ax.set_ylabel(label)
kwds = self.kwds.copy()
def blank_labeler(label, value):
if value == 0:
return ''
else:
return label
idx = [com.pprint_thing(v) for v in self.data.index]
labels = kwds.pop('labels', idx)
# labels is used for each wedge's labels
# Blank out labels for values of 0 so they don't overlap
# with nonzero wedges
if labels is not None:
blabels = [blank_labeler(l, value) for
l, value in zip(labels, y)]
else:
blabels = None
results = ax.pie(y, labels=blabels, **kwds)
if kwds.get('autopct', None) is not None:
patches, texts, autotexts = results
else:
patches, texts = results
autotexts = []
if self.fontsize is not None:
for t in texts + autotexts:
t.set_fontsize(self.fontsize)
# leglabels is used for legend labels
leglabels = labels if labels is not None else idx
for p, l in zip(patches, leglabels):
self._add_legend_handle(p, l)
def chartMultilineText(self, dev, p_dict, k_dict, text_to_plot, return_queue):
""""""
log = {'Threaddebug': [], 'Debug': [], 'Info': [], 'Warning': [], 'Critical': []}
try:
import textwrap
if self.verboseLogging:
log['Debug'].append(u"{0:<19}{1}".format("p_dict: ", [(k, v) for (k, v) in sorted(p_dict.items())]))
log['Debug'].append(u"{0:<19}{1}".format("k_dict: ", [(k, v) for (k, v) in sorted(k_dict.items())]))
p_dict['textColor'] = r"#{0}".format(p_dict['textColor'].replace(' ', '').replace('#', ''))
# If the value to be plotted is empty, use the default text from the device configuration.
if len(text_to_plot) <= 1:
text_to_plot = unicode(p_dict['defaultText'])
else:
# The cleanUpString method tries to remove some potential ugliness from the text to be plotted. It's optional--defaulted to on. No need to call this if the default text
# is used.
if p_dict['cleanTheText']:
text_to_plot = self.cleanUpString(text_to_plot)
# Wrap the text and prepare it for plotting.
text_to_plot = textwrap.fill(text_to_plot, int(p_dict['numberOfCharacters']), replace_whitespace=p_dict['cleanTheText'])
ax = self.chartMakeFigure(p_dict['figureWidth'], p_dict['figureHeight'], p_dict)
ax.text(0.01, 0.95, text_to_plot, transform=ax.transAxes, color=p_dict['textColor'], fontname=p_dict['fontMain'], fontsize=p_dict['multilineFontSize'],
verticalalignment='top')
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if not p_dict['textAreaBorder']:
[s.set_visible(False) for s in ax.spines.values()]
# Transparent Charts Fill
if p_dict['transparent_charts'] and p_dict['transparent_filled']:
ax.add_patch(patches.Rectangle((0, 0), 1, 1, transform=ax.transAxes, facecolor=p_dict['faceColor'], zorder=1))
# Chart title
plt.title(p_dict['chartTitle'], position=(0.5, 1.0), **k_dict['k_title_font'])
plt.tight_layout(pad=1)
plt.subplots_adjust(left=0.02, right=0.98, top=0.9, bottom=0.05)
if p_dict['fileName'] != '':
plt.savefig(u'{0}{1}'.format(p_dict['chartPath'], p_dict['fileName']), **k_dict['k_plot_fig'])
plt.clf()
plt.close('all')
return_queue.put({'Error': False, 'Log': log, 'Message': 'updated successfully.', 'Name': dev.name})
except (KeyError, IndexError, ValueError, UnicodeEncodeError) as sub_error:
return_queue.put({'Error': True, 'Log': log, 'Message': str(sub_error), 'Name': dev.name})
except Exception as sub_error:
return_queue.put({'Error': True, 'Log': log, 'Message': str(sub_error), 'Name': dev.name})
def visualize_run(XX, LL, UU, MM, name=None):
#-----plot the sequence of states for the test run
figure = plt.figure()
ax = figure.add_subplot(1,1,1)
N = len(XX)
#print 'N: %s' %N
#----
for n in xrange(0, N):
X = list(XX[n])
L = list(LL[n])
U = list(UU[n])
M = list(MM[n])
K = len(X)
#print 'K: %s' %K
RAD = 0.3
for k in xrange(0, K):
if M[k] == 0:
color = 'blue'
if M[k] == 1:
color = 'magenta'
if M[k] == 2:
color = 'black'
#----
rec = matplotlib.patches.Rectangle((4*k-RAD, 3*n-RAD),
RAD*2, RAD*2,
fill = False,
edgecolor = color,
linewidth = 3,
ls = 'solid',
alpha =1)
ax.add_patch(rec)
setstr = r''
for s in L[k]:
setstr += s
setstr +=','
ax.text(4*k-RAD, 3*n+RAD*4, r'$(%s, \{%s\})$' %(str(X[k]), str(setstr)), fontsize = 6, fontweight = 'bold')
#----
if (k<= K-2):
line = matplotlib.lines.Line2D([4*k+RAD,4*k+4-RAD],
[3*n, 3*n],
linestyle='-',
linewidth=1,
color='black')
ax.add_line(line)
actstr = r''
for s in U[k]:
actstr += s
ax.text(4*k+2, 3*n+RAD, r'%s' %str(actstr), fontsize = 6, fontweight = 'bold')
ax.set_aspect(0.7)
ax.set_xlim(-1, 4*K)
ax.set_ylim(-1, 3*N)
ax.set_xlabel(r'$state\; sequence$')
ax.set_ylabel(r'$run$')
#ax.axis('off')
if name:
plt.savefig('%s.pdf' %name,bbox_inches='tight')
return figure
def visualize_world(WS_d, WS_node_dict, name=None):
#----visualization for square-partitioned-workspace----
#----see case_study.py for details----
figure = plt.figure()
ax = figure.add_subplot(1,1,1)
#----- draw the workspace
for node, prop in WS_node_dict.iteritems():
if frozenset(['base1','base']) in prop.keys():
text = '$Base1$'
color = 'yellow'
elif frozenset(['base2','base']) in prop.keys():
text = '$Base2$'
color = 'yellow'
elif frozenset(['base3','base']) in prop.keys():
text = '$Base3$'
color = 'yellow'
elif frozenset(['obstacle','low']) in prop.keys():
text = '$Obs: 0.2$'
color = '#ff8000'
elif frozenset(['obstacle','top']) in prop.keys():
text = '$Obs: 1.0$'
color = 'red'
elif frozenset(['supply',]) in prop.keys():
text = '$Sply: %s$' %str(prop[frozenset(['supply',])])
if prop[frozenset(['supply',])]>=0.8:
color = '#0000ff'
elif prop[frozenset(['supply',])]>=0.6:
color = '#0040ff'
elif prop[frozenset(['supply',])]>=0.4:
color = '#0080ff'
elif prop[frozenset(['supply',])]>=0.2:
color = '#00bfff'
else:
text = None
color = 'white'
rec = matplotlib.patches.Rectangle((node[0]-WS_d, node[1]-WS_d),
WS_d*2, WS_d*2,
fill = True,
facecolor = color,
edgecolor = 'black',
linewidth = 1,
ls = '--',
alpha =0.8)
ax.add_patch(rec)
if text:
ax.text(node[0]-0.7, node[1], r'%s' %text, fontsize = 10, fontweight = 'bold')
ax.set_aspect('equal')
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_xlabel(r'$x(m)$')
ax.set_ylabel(r'$y(m)$')
if name:
plt.savefig('%s.pdf' %name,bbox_inches='tight')
return figure