def plot_stacked_barchart(self, dataframe, sort, title, xlable, ylable, kurs): x = [] tutor = [] y = [] for i in dataframe['tutor']: if i not in tutor: tutor.append(i) y.append([]) for i, elem in enumerate(dataframe[sort]): print(y, elem) if elem in x: y[tutor.index(dataframe['tutor'][i])][x.index(elem)] += 1 else: x.append(elem) for j, elem2 in enumerate(tutor): y[j].append(0) y[tutor.index(dataframe['tutor'][i])][x.index(elem)] += 1 for i, elem in enumerate(y): plt.bar(range(len(elem)), elem, label=tutor[i]) plt.xlabel(xlable) plt.ylabel(ylable) plt.legend(loc="best") plt.savefig('./PDFcreater/Plots/{}/{}.png'.format(kurs, title)) #plt.show() # loescht den Plot fuer den Naechsten Plot plt.clf() plt.cla() plt.close()
def plottrace(self, point): # 使用matplotlib之pyplot绘制船舶轨迹 # point = 38 def initial(ax): ax.axis("equal") #设置图像显示的时候XY轴比例 ax.set_xlabel('Horizontal Position') ax.set_ylabel('Vertical Position') ax.set_title('Vessel trajectory') plt.grid(True) #添加网格 return ax es_time = np.zeros([point]) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax = initial(ax) # test ax2 = fig.add_subplot(1, 1, 1) ax2 = initial(ax2) plt.ion() #interactive mode on 动态绘制 # IniObsX=0000 # IniObsY=4000 # IniObsAngle=135 # IniObsSpeed=10*math.sqrt(2) #米/秒 # print('开始仿真') obsX = [] obsX2 = [] # obsY = [4000,] obsY = [] obsY2 = [] for t in range(point): # t0 = time.time() #障碍物船只轨迹 # obsX.append(IniObsX+IniObsSpeed*math.sin(IniObsAngle/180*math.pi)*t) obsX.append(sim_res.SHIP1POS[t][0]) obsX2.append(sim_res.SHIP2POS[t][0]) # obsY.append(IniObsY+IniObsSpeed*math.cos(IniObsAngle/180*math.pi)*t) obsY.append(sim_res.SHIP1POS[t][1]) obsY2.append(sim_res.SHIP2POS[t][1]) plt.cla() ax = initial(ax) ax.plot(obsX, obsY, '-g', marker='*') #散点图 # test ax2 = initial(ax2) ax2.plot(obsX2, obsY2, '-r', marker='o') risk_value_text = 'Risk value: ' + str( sim_res.RISKVALUE[t]) plt.text(0, 7, risk_value_text) plt.pause(0.5) # es_time[t] = 1000*(time.time() - t0) plt.pause(0) # return es_time pass
def plot_pie(self, nx_dataframe, topic, se_title, kurs): gender = self.sort_column(nx_dataframe[topic]) labels = [gender[0][i] for i,elem in enumerate(gender[0])] fracs = [gender[1][i] for i,elem in enumerate(gender[1])] explode = [0.05 for i,elem in enumerate(gender[1])] plt.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=True) plt.savefig('./PDFcreater/Plots/{}/1{}.png'.format(kurs,se_title)) plt.clf() plt.cla() plt.close()
def plot_boring_barchart(self,dataframe,x,y,title,xlable,ylable, kurs): plt.bar(x, y, color='blue') #plt.title(title) plt.xlabel(xlable) plt.ylabel(ylable) plt.savefig('./PDFcreater/Plots/{}/{}.png'.format(kurs,title)) #loescht den Plot fuer den Naechsten Plot plt.clf() plt.cla() plt.close()
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')
z = np.array([pose_3d[i[0]][2], pose_3d[i[1]][2]]) ax.plot3D(x, y, z, 'red') def add_point(pose_3d, ax): x, y, z = pose_3d[:, 0], pose_3d[:, 1], pose_3d[:, 2] ax.scatter3D(x, y, z, cmap='Greens') import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes(projection='3d') plt.ion() i = 0 for pose_3d in pose_3d_all: add_line(pose_3d, ax) add_point(pose_3d, ax) square_x = np.array([-2000, 1000]) square_y = np.array([-1000, 2000]) square_z = np.array([500, 3500]) ax.scatter3D(square_x, square_y, square_z, color='whitesmoke') plt.draw() plt.pause(0.01) if i == 0: plt.pause(2) i += 1 plt.cla()
############################################################################################################## ##### using lstm ##### ############################################################################################################## # generates lstm model for s (takes about 1-2 minutes) : src = lol.weather_station(df_t, dhist, dhoriz, n_years_2train, 'lstm') start = src.data.index[src.year_train*365+src.dd_historic+src.dd_horizon] #first day after validation data end = df_t.index[-src.dd_horizon-1] Harvest, Harvest_hat = start, start for today in pd.date_range(start,end): ind_curr = pd.date_range(today-timedelta(dhist-1),today) x_input = df_t.loc[ind_curr] yhat = yhat = src.lstm_predict(x_input) plt.figure(1), plt.cla() x_input.plot(style='b-') df_t.loc[yhat.index].plot(style='g-') yhat.plot(style='r--') plt.pause(0.0001) ind_pred = yhat.index yhat = lol.gdd(df_t.loc[pd.date_range(today-timedelta(365),today)].append(yhat)) ind_curr_year = df_aGDD_s[df_aGDD_s.index. year == today.year].index Harvest = df_aGDD_s[ind_curr_year][df_aGDD_s[ind_curr_year] <= 500].index[-1].date() ind_curr_year = yhat[yhat.index. year == today.year].index Harvest_hat = yhat[ind_curr_year][yhat[ind_curr_year] <= 500].index[-1].date() plt.figure(2), plt.cla()
seismic_activity = np.array( [at, seismic_activity[7], seismic_activity[8], seismic_activity[-1]]) injection_wells = np.loadtxt(injWell_OK.txt).T at_bin = np.arange(dPar['tmin'], 2018, dPar['dt_map']) for i in range(at_bin.shape[0] - 1): t1, t2 = at_bin[i], at_bin[i + 1] sel_eq = np.logical_and(seismic_activity[0] >= t1, seismic_activity[0] < t2) sel_we = np.logical_and(injection_wells[1] <= t1, injection_wells[1] < t1) print(t1, t2, 'No. earthquakes', sel_eq.sum(), 'No. of wells', sel_we.sum()) #create basemap object matplotlib.figure(2) matplotlib.cla() ax2 = matplotlib.subplot(111) lon_0, lat_0 = .5 * (dPar['xmin'] + dPar['xmax']), .5 * (dPar['ymin'] + dPar['ymax']) m = Basemap( llcrnrlon=dPar['xmin'], urcrnrlon=dPar['xmax'], llcrnrlat=dPar['ymin'], urcrnrlat=dPar['ymax'], lon_0=lon_0, lat_0=lat_0, resolution='l', projection=dPar['projection'], ) m.drawcoastlines()