def stackedarea(series, **kwargs): fig = plt.figure() axe = fig.add_subplot(111) fnx = lambda s: np.array(list(v[1] for v in s), dtype="f8") yax = np.row_stack(fnx(s) for s in series) xax = np.arange(1917, 2008) polys = axe.stackplot(xax, yax) #创建子图对象后,调用对象的stackplot绘制箱线图 axe.margins(0, 0) if 'ylabels' in kwargs: axe.set_ylabel(kwargs['ylabel']) if 'labels' in kwargs: legendProxies = [] for poly in polys: legendProxies.append(plt.Rectangle(0, 0), 1, 1, fc=poly.get_factor()[0]) axe.legend([legendProxies, kwargs.get('labels')]) if 'title' in kwargs: plt.title(kwargs['title']) return fig
def plot_bus(fig, ax, bus: Bus, bus_vec, C, scale, stack_count, bar=True): w = 160 h = 40 active = bus_vec[0].cpu().item() loc = int(bus_vec[2].cpu().item()) crd = [bus.M.nodes[loc].crd[0], bus.M.nodes[loc].crd[1]] passengers = bus_vec[4:4 + bus.M.n_station].cpu().numpy() location_onehot = bus_vec[4 + bus.M.n_station:4 + bus.M.n_station * 2 + 1].cpu().numpy() route_onehot = bus_vec[4 + bus.M.n_station * 2 + 1:].cpu().numpy() capacity = bus.capacity ind = bus.ind # stack the buses if there are more than 1 at the same place crd[1] += h * stack_count rect_anchor = [crd[0] - w / 2, crd[1] - h / 2] scalex, scaley = scale font_size = scaley * 800 if bar: crd_base_bar = rect_anchor bar_x, bar_y = ax.transAxes.inverted().transform( ax.transData.transform(crd_base_bar)) crd_rect_vert = [crd_base_bar[0] + w, crd_base_bar[1] + h] bar_x_vert, bar_y_vert = ax.transAxes.inverted().transform( ax.transData.transform(crd_rect_vert)) bar_scale_x = bar_x_vert - bar_x bar_scale_y = bar_y_vert - bar_y ax_bar = fig.add_axes([bar_x, bar_y, bar_scale_x, bar_scale_y]) total_count = 0 for i, count in enumerate(passengers): ax_bar.barh([0], count, left=total_count, color=C[i]) total_count += count ax_bar.set_ylim(0, 0.1) ax_bar.set_xlim(0, capacity) ax_bar.axis('off') bus_color = 'k' if active else 'b' ax.add_patch( plt.Rectangle(rect_anchor, width=w, height=h, ec=bus_color, fc='w')) ax.text(crd[0] + w / 2 + 10, crd[1], "{}/{}".format(int(sum(passengers)), capacity), ha='left', va='center', fontsize=font_size, color=bus_color) ax.text(crd[0] - w / 2 - 10, crd[1], "#{}".format(ind), ha='right', va='center', fontsize=font_size, color=bus_color)
def _vis_proposals(im, dets, thresh=0.5): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return class_name = 'obj' im = im[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12, 12)) ax.imshow(im, aspect='equal') for i in inds: bbox = dets[i, :4] score = dets[i, -1] ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=3.5)) ax.text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') ax.set_title(('{} detections with ' 'p({} | box) >= {:.1f}').format(class_name, class_name, thresh), fontsize=14) plt.axis('off') plt.tight_layout() plt.draw()
def draw_boxes_on_image(image_path: str, boxes: np.ndarray, scores: np.ndarray, labels: np.ndarray, label_names: List[str], score_thresh: float = 0.5, save_path: str = 'result'): """Draw boxes on images.""" image = np.array(PIL.Image.open(image_path)) plt.figure() _, ax = plt.subplots(1) ax.imshow(image) image_name = image_path.split('/')[-1] print("Image {} detect: ".format(image_name)) colors = {} for box, score, label in zip(boxes, scores, labels): if score < score_thresh: continue if box[2] <= box[0] or box[3] <= box[1]: continue label = int(label) if label not in colors: colors[label] = plt.get_cmap('hsv')(label / len(label_names)) x1, y1, x2, y2 = box[0], box[1], box[2], box[3] rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, linewidth=2.0, edgecolor=colors[label]) ax.add_patch(rect) ax.text(x1, y1, '{} {:.4f}'.format(label_names[label], score), verticalalignment='bottom', horizontalalignment='left', bbox={ 'facecolor': colors[label], 'alpha': 0.5, 'pad': 0 }, fontsize=8, color='white') print("\t {:15s} at {:25} score: {:.5f}".format( label_names[int(label)], str(list(map(int, list(box)))), score)) image_name = image_name.replace('jpg', 'png') plt.axis('off') plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.savefig("{}/{}".format(save_path, image_name), bbox_inches='tight', pad_inches=0.0) plt.cla() plt.close('all')
def sim_pi(total_sim): np.random.seed( 0 ) #creating a random seed to save the previous random numbers generated x_new = [] #creating an empty list for x values y_new = [] #creating an empty list for y values circle = [ ] #creating an empty list to save the values that fall inside the circle radius = 0.5 cir_plot = plt.Circle((0.5, 0.5), 0.5, color='r', fill=False) #plotting a circle sq_plot = plt.Rectangle((0, 0), 1, 1, color='b', fill=False) #plotting a rectangle fig = plt.gcf() ax = fig.gca(adjustable='box') ax.set_aspect('equal') ax.add_artist(cir_plot) ax.add_artist(sq_plot) dots = 0 for i in np.arange(total_sim): x = np.random.rand(1, 1) y = np.random.rand(1, 1) x_new = np.append(x_new, x) y_new = np.append(y_new, y) if (x - 0.5)**2 + (y - 0.5)**2 < radius**2: circle = np.append(circle, "red") dots += 1 else: circle = np.append(circle, "blue") plot = plt.scatter(x_new, y_new, s=1.5, color=circle) pi_val = (dots / total_sim) * 4 diff = round(abs(pi_val - 3.14159), 4) print("This simulation gives a pi value of", str(pi_val) + ". The difference between the known pi value of", str(3.14) + " and our simulated value is", str(diff) + ".")
def graph_intervals( X_test, y, best_model, actual_label, lower_bound_label, upper_bound_label, interval_label, title, model_params, n=100, # x_axis_col="store_order_id", ): # Don't show plots. y_interval_predicted = best_model.predict(X_test) X = X_test.copy() pd.options.mode.chained_assignment = None X[lower_bound_label] = y_interval_predicted[0, :, 0] X[upper_bound_label] = y_interval_predicted[0, :, 1] # X[lower_bound_label] = best_model.forest.predict(X_test) # X[upper_bound_label] = best_model.forest.predict(X_test) X[actual_label] = y pd.options.mode.chained_assignment = "warn" plt.rcParams["figure.figsize"] = [9, 16] plt.rcParams["figure.dpi"] = 400 fig = plt.figure() X_sample_w_index = X.sample(n=n).sort_values(by=[actual_label]) X_sample = X_sample_w_index.reset_index() plt.plot(X_sample.index, X_sample[actual_label], "b.", markersize=10, label=u"Observations") plt.plot(X_sample.index, X_sample[lower_bound_label], "k-") plt.plot(X_sample.index, X_sample[upper_bound_label], "k-") plt.fill( np.concatenate([X_sample.index, X_sample.index[::-1]]), np.concatenate( [X_sample[upper_bound_label], X_sample[lower_bound_label][::-1]]), alpha=0.2, fc="b", ec="None", label=interval_label, ) contains = (len(X[(X[lower_bound_label] <= X[actual_label]) & (X[actual_label] <= X[upper_bound_label])].index) / len(X.index)) over_estimates = len( X[(X[lower_bound_label] > X[actual_label])].index) / len(X.index) under_estimates = len( X[(X[upper_bound_label] < X[actual_label])].index) / len(X.index) median_interval_width = (X[upper_bound_label] - X[lower_bound_label]).median() score = interval_score(y, y_interval_predicted) scores = (r"contains={0:.0%}" + "\n" + r"underestimates={1:.0%}" + "\n" + r"overestimates={2:.0%}" + "\n" + r"med_interval_width={3:.2f}" + "\n" + r"score={4:.2f}").format(contains, over_estimates, under_estimates, median_interval_width, score) extra = plt.Rectangle((0, 0), 0, 0, fc="w", fill=False, edgecolor="none", linewidth=0) plt.legend([extra], [scores], loc="upper left") plt.title(title + ":" + model_params) plt_filename = title + ":" + model_params + ".png" plt.savefig(plt_filename, bbox_inches="tight") plt.close(fig) return plt_filename