def show_all(): fig = plt.figure() host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) host.set_ylabel("Temperature") host.set_xlabel("Datetime") host.axis["right"].set_visible(False) host.set_ylim(25, 35) par1.set_ylabel("eCO2") par1.axis["right"].set_visible(True) par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) par1.set_ylim(400, 2000) par2.set_ylabel("TVOC") new_axisline = par2.get_grid_helper().new_fixed_axis par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=(60, 0)) par2.set_ylim(0, 1000) fig.add_axes(host) p1, = host.plot(temperatures, label="Temperature") p2, = par1.plot(eCO2s, label="eCO2") p3, = par2.plot(TVOCs, label="TVOC") host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right2"].label.set_color(p3.get_color()) plt.show()
def paraAxis(x, y, name, cnt): ax_para = ParasiteAxes(ax, sharex=ax) ax.parasites.append(ax_para) ax_para.axis['right'].set_visible(True) ax_paraD = ax_para.get_grid_helper().new_fixed_axis ax_para.set_ylabel(name) ax_para.axis['right'] = ax_paraD(loc='right', offset=(40 * cnt, 0), axes=ax_para) ax_para.plot(x, y, label=name, color=cname[cnt + 1]) plt.legend(loc=0)
def main(): wholeDir = 'E:/work/code/deepSpeech/pytorch_deepspeech/result/07-23-12-47/' mdir = wholeDir + 'm.txt' prefftdir = wholeDir + "fft.txt" #gradfile = os.path.join(wholeDir,folder, 'output_now') dimMeans, frameMeans, norm = getM_(mdir) #drawgradgraph(gradfile) lossdir = wholeDir + "loss.txt" ys = np.loadtxt(lossdir) xs = np.zeros_like(ys) for i in range(xs.shape[0]): xs[i] = i + 1 plt.scatter(xs, ys) plt.savefig(os.path.dirname(wholeDir) + '/loss.png', dpi=150) plt.clf() myloss = np.loadtxt(wholeDir + "loss.txt") m_loss = -np.loadtxt(wholeDir + "loss.txt") fig = plt.figure() host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.axis['right'].set_visible(False) par1.axis['right'].set_visible(True) par1.set_ylabel('m_entropy=∑log(m_ij))') par1.axis['right'].major_ticklabels.set_visible(True) par1.axis['right'].label.set_visible(True) fig.add_axes(host) host.set_xlabel('epoch') host.set_ylabel('|preOutput-TrueOutput|²') p1, = host.plot(xs, myloss, label='|preOutput-TrueOutput|²') p2, = par1.plot(xs, m_loss, label='m_entropy=∑log(m_ij)); ') plt.title("two parts of loss") host.legend() # 轴名称,刻度值的颜色 host.axis['left'].label.set_color(p1.get_color()) par1.axis['right'].label.set_color(p2.get_color()) plt.savefig(os.path.join(os.path.dirname(wholeDir), 'loss_two_parts.png'), dpi=150) plt.clf() Fftreader.mcolorDrawer(norm, '/m hot map', os.path.dirname(prefftdir)) #Fftreader.mcolorDrawer(norm, '/m hot map color', os.path.dirname(prefftdir)) #print('m, mean:',np.mean(norm),'max:',np.max(norm),'min:',np.min(norm),'std:',np.std(norm,ddof=1)) #print(np.max(norm)) makeVoice(prefftdir, dimMeans, frameMeans, norm)
def display(dates, cases, covid, vaccine): fig = plt.figure() host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) host.set_ylabel("Cases") host.axis["right"].set_visible(False) par1.axis["right"].set_visible(True) par1.set_ylabel("COVID - 19 Clicks") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) par2.set_ylabel("Vaccine Clicks") offset = (60, 0) new_axisline = par2.get_grid_helper().new_fixed_axis par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=offset) fig.add_axes(host) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d')) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=7)) p1, = host.plot(dates, cases, label="USA 7 Day Average") p2, = par1.plot(dates, covid, label="COVID Keyword Clicks") p3, = par2.plot(dates, vaccine, label="Vaccine Keyword Clicks") host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right2"].label.set_color(p3.get_color()) plt.setp(host.axis["bottom"].major_ticklabels, rotation=45, ha="right") plt.gcf().canvas.set_window_title('COVID-19 Cases vs. BI Search Queries') plt.show()
def drawCurveDonkey(intxtpath, outimgpath, title, xlabel='epoch', par1label='loss', par2label='accuracy(%)'): xs = [] p1s = [] p2s = [] with open(intxtpath, 'r') as fin: lines = [l.strip() for l in fin.readlines()] for line in lines: x, p1, p2 = line.split('\t') xs.append(int(x)) p1s.append(float(p1)) p2s.append(float(p2)) fig = plt.figure() host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.axis['right'].set_visible(False) par1.axis['right'].set_visible(True) par1.set_ylabel(par2label) par1.axis['right'].major_ticklabels.set_visible(True) par1.axis['right'].label.set_visible(True) fig.add_axes(host) host.set_xlabel(xlabel) host.set_ylabel(par1label) p1, = host.plot(np.array(xs), np.array(p1s), label=par1label) p2, = par1.plot(np.array(xs), np.array(p2s), label=par2label) plt.title(title) host.legend() host.axis['left'].label.set_color(p1.get_color()) par1.axis['right'].label.set_color(p2.get_color()) plt.savefig(outimgpath, dpi=150) plt.clf()
makeVoicefor_mask(music_mask_dirs, True, fftangle) myloss = np.loadtxt(os.path.join(wholeDir, folder, 'myloss.txt')) m_loss = np.loadtxt(os.path.join(wholeDir, folder, 'm_loss.txt')) m_mean = np.loadtxt(os.path.join(wholeDir, folder, 'm_mean.txt')) m_var = np.loadtxt(os.path.join(wholeDir, folder, 'm_var.txt')) fig = plt.figure() host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.axis['right'].set_visible(False) par1.axis['right'].set_visible(True) par1.set_ylabel('m_entropy=∑log(m_ij))') par1.axis['right'].major_ticklabels.set_visible(True) par1.axis['right'].label.set_visible(True) fig.add_axes(host) host.set_xlabel('epoch') host.set_ylabel('|preOutput-TrueOutput|²') p1, = host.plot(np.arange(len(myloss)), myloss / (K * T), label='|preOutput-TrueOutput|²') p2, = par1.plot(np.arange(len(m_loss)), m_loss / (K * T), label='m_entropy=∑log(m_ij)); ') plt.title("two parts of loss normalized /KT ") host.legend() # 轴名称,刻度值的颜色 host.axis['left'].label.set_color(p1.get_color())
def draw_city(city): select = "SELECT so2, no2, co, time_point FROM day_data WHERE cityname='" + city + "'" + "AND time_point Between '2019-02-01' AND '2019-03-01'" cur.execute(select) all_data = cur.fetchall() # 防止查不到数据 if len(all_data) != 0: # 准备数据 so2 = [] no2 = [] co = [] time_point = [] # 准备标签 for data in all_data: so2.append(int(data[0])) no2.append(int(data[1])) co.append(float(data[2])) time_point.append(str(data[3])) # 准备字体 my_font = fm.FontProperties( fname="F:\\Project\\Environment\\web\\php\\font\\simsun.ttc") fontcn = {'family': 'SimSun', 'size': 10} # 绘制气温变化 fig = plt.figure(figsize=(40, 8), dpi=80) ax_so2 = HostAxes( fig, [0, 0, 0.9, 0.9 ]) # 用[left, bottom, weight, height]的方式定义axes,0 <= l,b,w,h <= 1 # parasite addtional axes, share x ax_no2 = ParasiteAxes(ax_so2, sharex=ax_so2) ax_co = ParasiteAxes(ax_so2, sharex=ax_so2) ax_so2.parasites.append(ax_no2) ax_so2.parasites.append(ax_co) # invisible right axis of ax_so2 ax_so2.axis['right'].set_visible(False) ax_so2.axis['top'].set_visible(False) ax_no2.axis['right'].set_visible(True) ax_no2.axis['right'].major_ticklabels.set_visible(True) ax_no2.axis['right'].label.set_visible(True) # set label for axis ax_so2.set_ylabel("so2 μg/m3", fontdict=fontcn) ax_so2.set_xlabel("时间", fontdict=fontcn) ax_no2.set_ylabel("no2 μg/m3", fontdict=fontcn) ax_co.set_ylabel("CO mg/m3", fontdict=fontcn) co_axisline = ax_co.get_grid_helper().new_fixed_axis ax_co.axis['right2'] = co_axisline(loc='right', axes=ax_co, offset=(40, 0)) fig.add_axes(ax_so2) x1 = time_point x2 = [i for i in range(0, len(x1))] y1 = so2 y2 = no2 y3 = co ax_so2.plot(x1, y1, label='so2', color='#009966') ax_no2.plot(x2, y2, label='no2', color='#FFDE33') ax_co.plot(x2, y3, label='co', color='#FF9933') ax_so2.legend() ax_no2.axis['right'].label.set_color('#FFDE33') ax_co.axis['right2'].label.set_color('#FF9933') ax_no2.axis['right'].major_ticks.set_color('#FFDE33') ax_co.axis['right2'].major_ticks.set_color('#FF9933') ax_no2.axis['right'].major_ticklabels.set_color('#FFDE33') ax_co.axis['right2'].major_ticklabels.set_color('#FF9933') ax_no2.axis['right'].line.set_color('#FFDE33') ax_co.axis['right2'].line.set_color('#FF9933') # 添加图形标题 plt.title(city + '日二氧化硫、二氧化氮、一氧化碳浓度变化情况', loc='center', fontproperties=my_font) # 保存图片 plt.savefig("./../../article/image/pollution/" + city + ".png", bbox_inches='tight') # 显示图形 # show ann img plt.cla() # clear fig to show ann img saved_img = plt.imread("./../../article/image/pollution/" + city + ".png") # keep the origin image size dpi = 80.0 height, width, depth = saved_img.shape plt.figure(figsize=(width / dpi, height / dpi)) plt.axis('off') plt.imshow(saved_img) plt.show()
ax_cof.parasites.append(ax_load) #ax_cof.parasites.append(ax_cp) #ax_cof.parasites.append(ax_wear) #invisible right axis of ax_cof ax_cof.axis['right'].set_visible(False) ax_cof.axis['top'].set_visible(True) ax_temp.axis['right'].set_visible(True) ax_temp.axis['right'].major_ticklabels.set_visible(True) ax_temp.axis['right'].label.set_visible(True) #set label for axis ax_cof.set_ylabel('Compress Strength (Kgf/$\mathregular{m^2}$)', fontsize=20) ax_cof.set_xlabel('Addition of Waste Tire Rubber Powder (g)') ax_temp.set_ylabel('Porosity (%)', fontsize=20) ax_load.set_ylabel('Coef. of Permeability (cm/s)', fontsize=20) #ax_cp.set_ylabel('CP') #ax_wear.set_ylabel('Wear') load_axisline = ax_load.get_grid_helper().new_fixed_axis #cp_axisline = ax_cp.get_grid_helper().new_fixed_axis #wear_axisline = ax_wear.get_grid_helper().new_fixed_axis ax_load.axis['right2'] = load_axisline(loc='right', axes=ax_load, offset=(70, 0)) #ax_cp.axis['right3'] = cp_axisline(loc='right', axes=ax_cp, offset=(80,0)) #ax_wear.axis['right4'] = wear_axisline(loc='right', axes=ax_wear, offset=(120,0)) fig.add_axes(ax_cof)
# ax2 = ax1.twinx() # ax3 = ax1.twinx() fig = plt.figure(1) # main y ax_cof = HostAxes( fig, [0.05, 0.05, 0.8, 0.8 ]) #用[left, bottom, right, height]的方式定义axes,0 <= l,b,w,h <= 1 ax_cof.set_xlabel('month') ax_cof.set_ylabel('unit price') ax_cof.axis['bottom'].major_ticklabels.set_rotation(45) ax_cof.axis['bottom'].major_ticklabels.set_fontsize(5) # parasite addition axes, share x ax_1 = ParasiteAxes(ax_cof, sharex=ax_cof) ax_1.set_ylabel('deal count') # ax_2 = ParasiteAxes(ax_cof, sharex=ax_cof) # ax_2.set_ylabel('average area') ax_cof.axis['right'].set_visible(False) ax_cof.axis['top'].set_visible(False) # ax_cof.set_ylim(2.8, 3.2) # append axes ax_cof.parasites.append(ax_1) # ax_cof.parasites.append(ax_2) ax1_axisline = ax_1.get_grid_helper().new_fixed_axis # ax2_axisline = ax_2.get_grid_helper().new_fixed_axis ax_1.axis['right2'] = ax1_axisline(loc='right', axes=ax_1, offset=(0, 0))
ax_data.parasites.append(ax_cpu) ax_data.parasites.append(ax_mem) #ax_data.parasites.append(ax_bitrates) #ax_data.parasites.append(ax_wear) #invisible right axis of ax_data ax_data.axis['right'].set_visible(False) ax_data.axis['top'].set_visible(False) ax_cpu.axis['right'].set_visible(True) ax_cpu.axis['right'].major_ticklabels.set_visible(True) ax_cpu.axis['right'].label.set_visible(True) #set label for axis ax_data.set_ylabel('data') ax_data.set_xlabel('time (s)') ax_cpu.set_ylabel('cpu') ax_mem.set_ylabel('memory') #ax_bitrates.set_ylabel('bitrates') #ax_wear.set_ylabel('Wear') #new axsi line load_axisline = ax_mem.get_grid_helper().new_fixed_axis #cp_axisline = ax_bitrates.get_grid_helper().new_fixed_axis #wear_axisline = ax_wear.get_grid_helper().new_fixed_axis #axsi line padding on the right ax_mem.axis['right2'] = load_axisline(loc='right', axes=ax_mem, offset=(40, 0)) #ax_bitrates.axis['right3'] = cp_axisline(loc='right', axes=ax_bitrates, offset=(80,0)) #ax_wear.axis['right4'] = wear_axisline(loc='right', axes=ax_wear, offset=(120,0)) #add host axes to fig
str(names[i]) + "," + str(gdp_values[i]) + "," + str(edu_values[i]) + "\n") i += 1 f.close() fig = plt.figure(1) host = HostAxes(fig, [0.1, 0.1, 0.8, 0.8]) par1 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.set_ylabel("Density") host.set_xlabel("Distance") host.axis["right"].set_visible(True) par1.axis["right"].set_visible(True) par1.set_ylabel("Temperature") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) fig.add_axes(host) host.set_xlim(1975, 2010) host.set_ylim(0, 100) host.set_xlabel("GDP and Success rate") host.set_ylabel("GDP per five years (*2*10^10") par1.set_ylabel("Success Rate (%)") p1, = host.plot(names, gdp_values, label="GDP") p2, = par1.plot(names, edu_values, label="Success Rate")
def draw_city(city): select = "SELECT max, min, date FROM weather WHERE city='" + city + "'" + " AND date Between '2018年02月01日' AND '2018年02月28日'" cur.execute(select) all_data = cur.fetchall() # 防止查不到数据 if len(all_data) != 0: # 准备数据 max = [] min = [] time_point = [] # 准备标签 for data in all_data: max_temperature = str(data[0]) max.append(int(max_temperature[0:len(max_temperature) - 1])) min_temperature = str(data[1]) min.append(int(min_temperature[0:len(min_temperature) - 1])) time_point.append(str(data[2])) # 准备字体 my_font = fm.FontProperties( fname="F:\\Project\\Environment\\web\\php\\font\\simsun.ttc") fontcn = {'family': 'SimSun', 'size': 10} # 绘制气温变化 fig = plt.figure(figsize=(40, 8), dpi=80) ax_max = HostAxes( fig, [0, 0, 0.9, 0.9 ]) # 用[left, bottom, weight, height]的方式定义axes,0 <= l,b,w,h <= 1 # parasite addtional axes, share x ax_min = ParasiteAxes(ax_max, sharex=ax_max) ax_max.parasites.append(ax_min) # invisible right axis of ax_so2 ax_max.axis['right'].set_visible(False) ax_max.axis['top'].set_visible(False) ax_min.axis['right'].set_visible(True) ax_min.axis['right'].major_ticklabels.set_visible(True) ax_min.axis['right'].label.set_visible(True) # set label for axis ax_max.set_ylabel("摄氏度(℃)", fontdict=fontcn) ax_max.set_xlabel("时间", fontdict=fontcn) ax_min.set_ylabel("摄氏度(℃)", fontdict=fontcn) fig.add_axes(ax_max) x1 = time_point x2 = [i for i in range(0, len(time_point))] y1 = max y2 = min ax_max.plot(x1, y1, label='最高温度', color='#009966') ax_min.plot(x2, y2, label='最低温度', color='#FFDE33') ax_max.legend() ax_min.axis['right'].label.set_color('#FFDE33') ax_min.axis['right'].major_ticks.set_color('#FFDE33') ax_min.axis['right'].major_ticklabels.set_color('#FFDE33') ax_min.axis['right'].line.set_color('#FFDE33') # 添加图形标题 plt.title(city + '最高温度和最低温度变化情况', loc='center', fontproperties=my_font) # 保存图片 plt.savefig("./../../article/image/temperature/" + city + ".png", bbox_inches='tight') # 显示图形 # show ann img plt.cla() # clear fig to show ann img saved_img = plt.imread("./../../article/image/temperature/" + city + ".png") # keep the origin image size dpi = 80.0 height, width, depth = saved_img.shape plt.figure(figsize=(width / dpi, height / dpi)) plt.axis('off') plt.imshow(saved_img) plt.show()
def dym_quantile(n): """ 动态分位图 当前投资已5年内历史数据计算百分位,价格合适购入 """ # 这里的计算按一年244个交易日计算 windows = int(n * 244) # 将时间取整数 start_date = dt.datetime(2006, 1, 1) end_date = dt.datetime(2020, 4, 1) df = dp.load_bar_data('000300', 'XSHG', start_date=start_date, end_data=end_date) df_finance = dp.load_finance_data('000300.XSHG', start_date=start_date, end_date=end_date) if len(df) == len(df_finance): print('yes!!!, len:%s' % len(df)) df['pe'] = df_finance['pe'] df['quantile'] = df_finance['pe'].rolling(windows).apply(lambda x: pd.Series(x).rank().iloc[-1] / pd.Series(x).shape[0], raw=True) # df['date'] = pd.to_datetime(df['date']) # 转换时间类型 # df.set_index(['date'], inplace=True) # df.index.name = None # 去掉索引列名 df.dropna(inplace=True) # 画出适中估值区间 # plt.figure() # 创建第一个画板 fig = plt.figure(figsize=(16, 9)) host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) host.set_xlabel('Date') host.set_ylabel('Close') host.axis['right'].set_visible(False) par1.axis['right'].set_visible(True) par1.set_ylabel('%sY Rolling quantile' % n) par1.axis['right'].major_ticklabels.set_visible(True) par1.axis['right'].label.set_visible(True) par2.set_ylabel('PE') new_axisline = par2.get_grid_helper().new_fixed_axis # "_grid_helper"与"get_grid_helper()"等价,可以代替 par2.axis['right2'] = new_axisline(loc='right', axes=par2, offset=(45, 0)) fig.add_axes(host) df['date'] = pd.to_datetime(df['date']) df['date'] = df['date'].apply(lambda x: dates.date2num(x)) p1, = host.plot(df['date'], df['close'], label="Close") p2, = par1.plot(df['date'], df['quantile'], label="Quantile") p3, = par2.plot(df['date'], df['pe'], label="PE") host.legend() # 轴名称,刻度值的颜色 host.axis['left'].label.set_color(p1.get_color()) host.xaxis.set_major_locator(ticker.MaxNLocator(math.floor(len(df) / 100))) host.xaxis.set_major_formatter(dates.DateFormatter('%Y-%m')) par1.axis['right'].label.set_color(p2.get_color()) par2.axis['right2'].label.set_color(p3.get_color()) par2.axis['right2'].major_ticklabels.set_color(p3.get_color()) # 刻度值颜色 par2.axis['right2'].set_axisline_style('-|>', size=1.5) # 轴的形状色 par2.axis['right2'].line.set_color(p3.get_color()) # 轴的颜色 # ax.xaxis.set_major_formatter(dates.DateFormatter('%Y-%m-%d')) # df[['quantile', 'close']].plot(secondary_y=['quantile'], figsize=(14, 10), alpha=.8) # plt.fill_between(df.index, y1=0.4, y2=0.6, color='blue', alpha=0.7) # plt.fill_between(df.index, y1=0.8, y2=1, color='red', alpha=0.7) # plt.fill_between(df.index, y1=0.0, y2=0.2, color='green', alpha=0.7) # plt.annotate('reasonable zone', (df.index[-1], 0.5)) # 画出固定PE与收盘价的曲线 plt.show()
host.axis["right"].set_visible(False) par1.axis["right"].set_visible(True) par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) fig1.add_axes(host) host.set_xlim(np.pi / 2, np.pi) host.set_ylim(0.29, 0.61) host.set_xticks([1.57, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.1415]) host.set_xticklabels( ['$\\pi/2$', '1.8', '2.0', '2.2', '2.4', '2.6', '2.8', '3.0', '$\\pi$']) host.set_xlabel("$\\theta_c$") host.set_ylabel("$\\theta_b^*$") par1.set_ylabel("min$_{\\theta_b} \\varepsilon$ $(\\times 10^{-3})$") p1, = host.plot(C[0, :], X[Z.argmin(axis=0), 0], label="$\\theta_b^*$", color='#1f77b4') p2, = par1.plot(C[0, :], Z.min(axis=0) * 1000, label="min$_{\\theta_b} \\varepsilon$", color='#e6550d') par1.set_ylim(0, 2.5) host.legend(loc='center left') host.grid(linestyle='--') host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color())
simplejson.dump(values1, f) f.write('\n') simplejson.dump(values2, f) f.close() fig = plt.figure(1) host = HostAxes(fig, [0.1, 0.1, 0.8, 0.8]) par1 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.set_ylabel("Density") host.set_xlabel("Distance") host.axis["right"].set_visible(True) par1.axis["right"].set_visible(True) par1.set_ylabel("Temperature") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) fig.add_axes(host) host.set_xlim(1975, 2010) host.set_ylim(0, 100) host.set_xlabel("Years Intervals") host.set_ylabel("Income") par1.set_ylabel("Pass Rate") p1, = host.plot(names, values1, label="Income") p2, = par1.plot(names, values2, label="Pass Rate")
line_torque_multi_gear = ax_torque_multi_gear.plot( time[order], torque_multi_gear, linestyle=line_style[vehicle_number[order]], color=line_color[temperature_target[order]]) gear_max = max(gear_max, max(gear[order])) power_max = max(power_max, max(power)) lines_set = lines_set + line_power legend_set = [line.get_label() for line in lines_set] ax_power.legend(lines_set, legend_set, loc='upper left') ax_power.set_xlabel('Time(s)') ax_power.set_ylabel('Power(kw)') ax_power.set_ylim(-20, 2 * power_max) ax_power.set_yticks([i * 20 for i in range(0, int(power_max / 20 + 1))]) ax_gear.set_ylabel('Gear/Gear ratio') ax_gear.set_ylim(-gear_max, gear_max + 1) ax_gear.set_yticks([i for i in range(0, int(gear_max) + 1)]) if gear_max > 10: # if it is gear ratio, plot torque*gear ax_torque_multi_gear.set_ylabel('Torque*gear ratio(Nm)') ax_torque_multi_gear.set_ylim(-torque_mutil_gear_max - 50, torque_mutil_gear_max) ax_torque_multi_gear.set_yticks( [i * 500 for i in range(0, int(torque_mutil_gear_max / 500) + 2)]) ax_gear.set_ylim(0, 2 * gear_max) ax_power.legend(lines_set, legend_set, loc='upper right') plt.savefig(fig2_name + '.png', transparent=True) # plt.show()
if __name__ == "__main__": fig = plt.figure(1) host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) host.set_ylabel("Density") host.set_xlabel("Distance") host.axis["right"].set_visible(False) par1.axis["right"].set_visible(True) par1.set_ylabel("Temperature") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) par2.set_ylabel("Velocity") offset = (60, 0) new_axisline = par2._grid_helper.new_fixed_axis par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=offset) fig.add_axes(host) host.set_xlim(0, 2) host.set_ylim(0, 2) host.set_xlabel("Distance")
axis_cpu = ParasiteAxes(host, sharex=host) axis_response = ParasiteAxes(host, sharex=host) axis_container = ParasiteAxes(host, sharex=host) axis_throughput = ParasiteAxes(host, sharex=host) host.parasites.append(axis_cpu) host.parasites.append(axis_response) host.parasites.append(axis_container) host.parasites.append(axis_throughput) #关闭主图的左右上轴线,打开辅轴的右边线 host.axis['left'].set_visible(False) host.axis['right'].set_visible(False) host.axis['top'].set_visible(False) #设置各个轴线标签 host.set_xlabel('Time (20s)') axis_cpu.set_ylabel('CPU Utilization') axis_response.set_ylabel('Response Time') axis_container.set_ylabel('Number of Instances') axis_throughput.set_ylabel('Throughput') #添加辅轴 cpu_axisline = axis_cpu._grid_helper.new_fixed_axis response_axisline = axis_response._grid_helper.new_fixed_axis container_axisline = axis_container._grid_helper.new_fixed_axis throughput_axisline = axis_throughput._grid_helper.new_fixed_axis axis_cpu.axis['right2'] = cpu_axisline(loc='right', axes=axis_cpu, offset=(0, 0)) axis_response.axis['right3'] = response_axisline(loc='right', axes=axis_response, offset=(40, 0)) axis_container.axis['right4'] = container_axisline(loc='right',
ax_cof.parasites.append(ax_temp) ax_cof.parasites.append(ax_load) ax_cof.parasites.append(ax_cp) ax_cof.parasites.append(ax_wear) #invisible right axis of ax_cof ax_cof.axis['right'].set_visible(False) ax_cof.axis['top'].set_visible(False) ax_temp.axis['right'].set_visible(True) ax_temp.axis['right'].major_ticklabels.set_visible(True) ax_temp.axis['right'].label.set_visible(True) #set label for axis ax_cof.set_ylabel('cof') ax_cof.set_xlabel('Distance (m)') ax_temp.set_ylabel('Temperature') ax_load.set_ylabel('load') ax_cp.set_ylabel('CP') ax_wear.set_ylabel('Wear') load_axisline = ax_load.get_grid_helper().new_fixed_axis cp_axisline = ax_cp.get_grid_helper().new_fixed_axis wear_axisline = ax_wear.get_grid_helper().new_fixed_axis ax_load.axis['right2'] = load_axisline(loc='right', axes=ax_load, offset=(40, 0)) ax_cp.axis['right3'] = cp_axisline(loc='right', axes=ax_cp, offset=(80, 0)) ax_wear.axis['right4'] = wear_axisline(loc='right', axes=ax_wear, offset=(120, 0))
#plt.xticks([]) host.axis["top"].major_ticks.set_color('white') par1.axis["right"].set_visible(True) #par1.set_ylabel("Runtime") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) #par2.set_ylabel("Velocity") #offset = (60, 0) #new_axisline = par2.get_grid_helper().new_fixed_axis #par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=offset) fig.add_axes(host) host.set_xlim(0, 80) host.set_ylim(0.6, 0.8) host.set_xlabel("Number of filter size") host.set_ylabel("F1 score") par1.set_ylabel("Runtime") #p1, = host.plot([1, 5, 10, 15, 20, 25, 30, 35, 40,50,60,70,80,90,100], [0.66, 0.736, 0.764, 0.778, 0.786, 0.814, 0.786, 0.783, 0.787,0.791,0.789,0.785,0.790,0.792,0.786], 'o-',label="F1 score", linewidth=2.2, color="#59604C") #p2, = par1.plot([1, 5, 10, 15, 20, 25, 30, 35, 40,50,60,70,80,90,100], [3.52, 3.68, 3.71, 3.72, 3.84, 3.85, 3.87, 3.96, 3.86,3.876,3.83,3.83,3.89,3.97,4.04], '*--', label="Runtime", linewidth=2.2, color="#A35638") p1, = host.plot([1, 5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80], [ 0.691, 0.693, 0.710, 0.715, 0.721, 0.727, 0.703, 0.704, 0.705, 0.695, 0.706, 0.687, 0.679 ], 'o-', label="F1 score", linewidth=2.2, color="#59604C") p2, = par1.plot([1, 5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80], [ 5.13, 5.28, 5.33, 5.76, 5.99, 6.01, 6.54, 6.83, 6.99, 7.38, 7.85, 7.97, 8.42 ], '*--',
def plot_vel_acc_rdis(vel, acc, rdis): title_font_dict = { 'family': 'Times New Roman', 'color': 'black', 'weight': 'normal', 'fontsize': 15 } axis_font_dict = { 'family': 'Times New Roman', 'color': 'black', 'weight': 'normal', 'fontsize': 30 } legend_font = { 'family': 'Times New Roman', 'weight': 'normal', 'size': 10, } vel_x = np.array(vel)[:, 0] / 10. vel_y = np.array(vel)[:, 1] acc_x = np.array(acc)[:, 0] / 10. acc_y = np.array(acc)[:, 1] rdis_x = np.array(rdis)[:, 0] / 10. rdis_y = np.array(rdis)[:, 1] fig = plt.figure(figsize=(10, 3.5), dpi=200) vel_axes = HostAxes(fig, [0.05, 0.1, 0.8, 0.8]) acc_axes = ParasiteAxes(vel_axes, sharex=vel_axes) rdis_axes = ParasiteAxes(vel_axes, sharex=vel_axes) vel_axes.parasites.append(acc_axes) vel_axes.parasites.append(rdis_axes) vel_axes.set_ylabel('Velocity (m/s)') vel_axes.set_xlabel('Time (s)') vel_axes.axis['right'].set_visible(False) acc_axes.axis['right'].set_visible(True) acc_axes.set_ylabel('Acceleration (m/s^2)') acc_axes.axis['right'].major_ticklabels.set_visible(True) acc_axes.axis['right'].label.set_visible(True) rdis_axes.set_ylabel('Relative distance (m)') offset = (60, 0) new_axisline = rdis_axes._grid_helper.new_fixed_axis rdis_axes.axis['right2'] = new_axisline(loc='right', axes=rdis_axes, offset=offset) fig.add_axes(vel_axes) p1, = vel_axes.plot(vel_x, vel_y, label="Vel", linewidth=2) p2, = acc_axes.plot(acc_x, acc_y, label="Acc", linewidth=2) p3, = rdis_axes.plot(rdis_x, rdis_y, label="RD", linewidth=2) vel_axes.legend(prop=legend_font) vel_axes.set_ylim(0, np.max(vel_y) + 1) vel_axes.set_xlim(0, np.max(vel_x)) rdis_axes.set_ylim(0, np.max(rdis_y) + 1) # plt.plot(vel_x, vel_y, color="green", label="Velocity", linewidth=2) # plt.ylabel('Velocity (m/s)', fontdict=axis_font_dict) # # plt.plot(acc_x, acc_y, color="orange", label="Acceleration", linewidth=2, secondary_y=True) # plt.ylabel('Acceleration (m/s^2)', fontdict=axis_font_dict) # plt.title('Kinematic information of host vehicle', fontdict=title_font_dict) # plt.xlabel('Time (s)', fontdict=axis_font_dict) # plt.ylabel('Likelihood', fontdict=axis_font_dict) # plt.tick_params(labelsize=20) plt.legend(prop=legend_font) # plt.ylim(0., 1.) # left, right = plt.xlim() # plt.xlim(0., right) plt.show() pass
<<<<<<< HEAD fig = plt.figure(1) ======= fig = plt.figure(figsize=(9, 5)) >>>>>>> f5b55f5735c94ec9573668b5d56b78a8eef2e8f7 host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) <<<<<<< HEAD host.set_ylabel('扬程') host.set_xlabel('流量') host.axis['right'].set_visible(False) par1.axis['right'].set_visible(True) par1.set_ylabel('功率') ======= host.set_ylabel('效率(E)(%)', color="blue") host.set_xlabel('流量(Q)(m3/h)') host.axis['right'].set_visible(False) par1.axis['right'].set_visible(True) par1.set_ylabel('功率(P)(kW)', color="red") >>>>>>> f5b55f5735c94ec9573668b5d56b78a8eef2e8f7 par1.axis['right'].major_ticklabels.set_visible(True) par1.axis['right'].label.set_visible(True) <<<<<<< HEAD par2.set_ylabel('扬程') ======= par2.set_ylabel('效率(E)(%)', color="blue")
fig = plt.figure(1) host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) host.set_ylabel("Density") host.set_xlabel("Distance") host.axis["right"].set_visible(False) par1.axis["right"].set_visible(True) par1.set_ylabel("Temperature") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) par2.set_ylabel("Velocity") offset = (60, 0) new_axisline = par2._grid_helper.new_fixed_axis par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=offset) fig.add_axes(host) host.set_xlim(0, 2) host.set_ylim(0, 2) host.set_xlabel("Distance")
def plot_multi_y(line_series_list, line_label_list, scatter_series_list, scatter_label_list): """ 第一条line做主轴,散点与主轴共用Y轴 :param line_series_list: :param line_label_list: :param scatter_series_list: :param scatter_label_list: :return: """ color_list = ['red', 'green', 'blue', 'yellow', 'pink', 'black', 'orange'] fig = plt.figure(1) host_axes = HostAxes(fig, [0.1, 0.1, 0.6, 0.8]) fig.add_axes(host_axes) host_axes.set_ylabel(line_label_list[0]) host_axes.axis['right'].set_visible(False) host_axes.set_ylim( min(line_series_list[0][1]) * 0.9, max(line_series_list[0][1]) * 1.1) host_axes.plot(line_series_list[0][0], line_series_list[0][1], label=line_label_list[0], color=color_list[0]) label_offset = 0 # line_axes = [] for i in range(len(line_series_list) - 1): axes = ParasiteAxes(host_axes, sharex=host_axes) axes.set_ylabel(line_label_list[i + 1]) axis_line = axes.get_grid_helper().new_fixed_axis axes.axis['right' + str(label_offset)] = axis_line( loc='right', axes=axes, offset=(label_offset, 0)) axes.axis['right' + str(label_offset)].label.set_color(color_list[i + 1]) axes.axis['right' + str(label_offset)].major_ticks.set_color( color_list[i + 1]) axes.axis['right' + str(label_offset)].major_ticklabels.set_color( color_list[i + 1]) axes.axis['right' + str(label_offset)].line.set_color(color_list[i + 1]) label_offset += 40 axes.set_ylim( min(line_series_list[i + 1][1]) * 0.9, max(line_series_list[i + 1][1]) * 1.1) axes.plot(line_series_list[i + 1][0], line_series_list[i + 1][1], label=line_label_list[i + 1], color=color_list[i + 1]) # line_axes.append(axes) host_axes.parasites.append(axes) # scatter_axes = [] for i in range(len(scatter_series_list)): # 与主轴共用Y轴 # axes = ParasiteAxes(host_axes, sharex=host_axes) # axes.set_ylabel(scatter_label_list[i]) # axis_line = axes.get_grid_helper().new_fixed_axis # axes.axis['right' + str(label_offset)] = axis_line(loc='right', axes=axes, offset=(label_offset, 0)) color_item = color_list[len(line_label_list) + i + 1] # axes.axis['right' + str(label_offset)].label.set_color(color_item) # axes.axis['right' + str(label_offset)].major_ticks.set_color(color_item) # axes.axis['right' + str(label_offset)].major_ticklabels.set_color(color_item) # axes.axis['right' + str(label_offset)].line.set_color(color_item) # label_offset += 40 # axes.set_ylim(min(scatter_series_list[i][1]), max(scatter_series_list[i][1])) host_axes.scatter(scatter_series_list[i][0], scatter_series_list[i][1], label=scatter_label_list[i], color=color_item) # scatter_axes.append(axes) # host_axes.parasites.append(axes) host_axes.legend() plt.show()
def line_graph(self): ords = [i.text() for i in self.temp_variables_w if i.checkState()] if not len(ords): return absc = self.ui.lineComboW.currentText() def values(s): return self.simulation.state_fct[self.temporal_variables[s][0]] def label(s): if len(self.temporal_variables[s])>1: return s + " (" + self.temporal_variables[s][1] + ")" return s def dimension(s): if "energy" in s: return "Energy (J)" elif "Temperature" in s: return "Temperature (K)" else: return label(s) dimensions = list(set(dimension(s) for s in ords)) axis = dict() visu.plt.ioff() fig = visu.plt.figure() gr_opts = dict() for o in self._1d_options: gr_opts[o] = self._1d_options[o].checkState() host = HostAxes(fig, [0.15, 0.1, 0.75-(0.04*len(dimensions)), 0.8]) host.set_xlabel(label(absc)) host.set_ylabel(dimensions[0]) if gr_opts["log x"]: host.semilogx() if gr_opts["log y"]: host.semilogy() if gr_opts["grid"]: host.grid(True, which="minor", linestyle="--") host.grid(True, which="major") if len(dimensions)>1: host.axis["right"].set_visible(False) axis[dimensions[0]] = host for i, dim in enumerate(dimensions[1:]): par = ParasiteAxes(host, sharex=host) host.parasites.append(par) par.axis["right"] = par.get_grid_helper().new_fixed_axis(loc="right", axes=par, offset=(55*i, 0)) par.axis["right"].set_visible(True) par.set_ylabel(dim) par.axis["right"].major_ticklabels.set_visible(True) par.axis["right"].label.set_visible(True) axis[dim] = par if gr_opts["log x"]: par.semilogx() if gr_opts["log y"]: par.semilogy() for i in ords: axis[dimension(i)].plot(values(absc), values(i), label=label(i)) fig.add_axes(host) host.legend() visu.plt.show()
def draw_point_fcst(t2m=None, u10m=None, v10m=None, rn=None, model=None, output_dir=None, points=None, extra_info=None): plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体) plt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题) if (sys.platform[0:3] == 'lin'): locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8') if (sys.platform[0:3] == 'win'): locale.setlocale(locale.LC_CTYPE, 'chinese') initTime = pd.to_datetime(str( t2m['forecast_reference_time'].values)).replace( tzinfo=None).to_pydatetime() # draw figure fig = plt.figure(figsize=(16, 4.5)) ax_t2m = HostAxes(fig, [0.1, 0.28, .8, .62]) ax_rn = ParasiteAxes(ax_t2m, sharex=ax_t2m) #其他信息 #append axes ax_t2m.parasites.append(ax_rn) #invisible right axis of ax ax_t2m.axis['right'].set_visible(False) ax_t2m.axis['right'].set_visible(False) ax_rn.axis['right'].set_visible(True) ax_rn.axis['right'].major_ticklabels.set_visible(True) ax_rn.axis['right'].label.set_visible(True) #set label for axis ax_t2m.set_ylabel('温度($^\circ$C)', fontsize=100) ax_rn.set_ylabel('降水(mm)', fontsize=100) fig.add_axes(ax_t2m) # draw main figure #2米温度—————————————————————————————————————— if (model == '中央台指导'): model = '智能网格' utl.add_public_title_sta(title=model + '预报 ' + extra_info['point_name'] + ' [' + str(points['lon'][0]) + ',' + str(points['lat'][0]) + ']', initTime=initTime, fontsize=21) for ifhour in t2m['forecast_period'].values: if (ifhour == t2m['forecast_period'].values[0]): t2m_t = (initTime + timedelta(hours=ifhour)) else: t2m_t = np.append(t2m_t, (initTime + timedelta(hours=ifhour))) curve_t2m = ax_t2m.plot(t2m_t, np.squeeze(t2m['data'].values), c='#FF6600', linewidth=3, label='2m温度') ax_t2m.set_xlim(t2m_t[0], t2m_t[-1]) ax_t2m.set_ylim( math.floor(t2m['data'].values.min() / 5) * 5 - 2, math.ceil(t2m['data'].values.max() / 5) * 5) #降水—————————————————————————————————————— for ifhour in rn['forecast_period'].values: if (ifhour == rn['forecast_period'].values[0]): rn_t = (initTime + timedelta(hours=ifhour)) else: rn_t = np.append(rn_t, (initTime + timedelta(hours=ifhour))) mask = (rn['data'] < 999) rn = rn['data'].where(mask) ax_rn.bar(rn_t, np.squeeze(rn.values), width=0.1, color='#00008B', label=str( int(rn['forecast_period'].values[1] - rn['forecast_period'].values[0])) + '小时降水', alpha=0.5) #curve_rn=ax_rn.plot(rn_t, np.squeeze(rn['data'].values), c='#40C4FF',linewidth=3) ax_rn.set_ylim(0, np.nanmax(np.append(10, np.squeeze(rn.values)))) ### xaxis_intaval = mpl.dates.HourLocator(byhour=(8, 20)) #单位是小时 ax_t2m.xaxis.set_major_locator(xaxis_intaval) # add legend ax_t2m.legend(fontsize=15, loc='upper right') ax_t2m.tick_params(length=10) ax_t2m.tick_params(axis='y', labelsize=100) ax_t2m.set_xticklabels([' ']) miloc = mpl.dates.HourLocator(byhour=(8, 11, 14, 17, 20, 23, 2, 5)) #单位是小时 ax_t2m.xaxis.set_minor_locator(miloc) yminorLocator = MultipleLocator(1) #将此y轴次刻度标签设置为1的倍数 ax_t2m.yaxis.set_minor_locator(yminorLocator) ymajorLocator = MultipleLocator(5) #将此y轴次刻度标签设置为1的倍数 ax_t2m.yaxis.set_major_locator(ymajorLocator) ax_t2m.grid(axis='x', which='minor', ls='--') ax_t2m.axis['left'].label.set_fontsize(15) ax_t2m.axis['left'].major_ticklabels.set_fontsize(15) ax_rn.axis['right'].label.set_fontsize(15) ax_rn.axis['right'].major_ticklabels.set_fontsize(15) #10米风—————————————————————————————————————— ax_uv = plt.axes([0.1, 0.16, .8, .12]) for ifhour in u10m['forecast_period'].values: if (ifhour == u10m['forecast_period'].values[0]): uv_t = (initTime + timedelta(hours=ifhour)) else: uv_t = np.append(uv_t, (initTime + timedelta(hours=ifhour))) wsp = (u10m**2 + v10m**2)**0.5 #curve_uv=ax_uv.plot(uv_t, np.squeeze(wsp['data'].values), c='#696969',linewidth=3,label='10m风') ax_uv.barbs(uv_t, np.zeros(len(uv_t)), np.squeeze(u10m['data'].values), np.squeeze(v10m['data'].values), fill_empty=True, color='gray', barb_increments={ 'half': 2, 'full': 4, 'flag': 20 }, length=5.8, linewidth=1.5, zorder=100) ax_uv.set_ylim(-1, 1) ax_uv.set_xlim(uv_t[0], uv_t[-1]) #ax_uv.axis('off') ax_uv.set_yticklabels([' ']) #logo utl.add_logo_extra_in_axes(pos=[0.87, 0.00, .1, .1], which='nmc', size='Xlarge') #开启自适应 xaxis_intaval = mpl.dates.HourLocator(byhour=(8, 20)) #单位是小时 ax_uv.xaxis.set_major_locator(xaxis_intaval) ax_uv.tick_params(length=5, axis='x') ax_uv.tick_params(length=0, axis='y') miloc = mpl.dates.HourLocator(byhour=(8, 11, 14, 17, 20, 23, 2, 5)) #单位是小时 ax_uv.xaxis.set_minor_locator(miloc) ax_uv.grid(axis='x', which='both', ls='--') ax_uv.set_ylabel('10m风', fontsize=15) xstklbls = mpl.dates.DateFormatter('%m月%d日%H时') for label in ax_uv.get_xticklabels(): label.set_rotation(30) label.set_horizontalalignment('center') ax_uv.tick_params(axis='x', labelsize=15) #出图—————————————————————————————————————————————————————————— if (output_dir != None): isExists = os.path.exists(output_dir) if not isExists: os.makedirs(output_dir) output_dir2 = output_dir + model + '_起报时间_' + initTime.strftime( "%Y年%m月%d日%H时") + '/' if (os.path.exists(output_dir2) == False): os.makedirs(output_dir2) plt.savefig(output_dir2 + model + '_' + extra_info['point_name'] + '_' + extra_info['output_head_name'] + initTime.strftime("%Y%m%d%H") + '00' + extra_info['output_tail_name'] + '.jpg', dpi=200, bbox_inches='tight') else: plt.show()