def plot_stat(rows, cache): "Use matplotlib to plot DAS statistics" if not PLOT_ALLOWED: raise Exception('Matplotlib is not available on the system') if cache in ['cache', 'merge']: # cachein, cacheout, mergein, mergeout name_in = '%sin' % cache name_out = '%sout' % cache else: # webip, webq, cliip, cliq name_in = '%sip' % cache name_out = '%sq' % cache def format_date(date): "Format given date" val = str(date) return '%s-%s-%s' % (val[:4], val[4:6], val[6:8]) date_range = [r['date'] for r in rows] formated_dates = [format_date(str(r['date'])) for r in rows] req_in = [r[name_in] for r in rows] req_out = [r[name_out] for r in rows] plt.plot(date_range, req_in , 'ro-',\ date_range, req_out, 'gv-',) plt.grid(True) plt.axis([min(date_range), max(date_range), \ 0, max([max(req_in), max(req_out)])]) plt.xticks(date_range, tuple(formated_dates), rotation=17) # plt.xlabel('dates [%s, %s]' % (date_range[0], date_range[-1])) plt.ylabel('DAS %s behavior' % cache) plt.savefig('das_%s.pdf' % cache, format='pdf', transparent=True) plt.close()
def plot_comfort(fingers_org=range(1, 6, 1), fingers_dst=range(1, 6, 1), jumps=range(-12, 13, 1)): import seaborn from mpl_toolkits.mplot3d import Axes3D from pylab import plt xs, ys, zs, cs = calculate_comforts(fingers_org, fingers_dst, jumps) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xs, ys, zs, c=cs) ax.set_zlabel("Interval (half steps)", fontsize=15) ax.set_zlim(jumps[0], jumps[-1]) # ax.set_zticks(jumps) plt.xticks(fingers_org) plt.xlim(fingers_org[0], fingers_org[-1]) plt.xlabel("From finger", fontsize=15) plt.yticks(fingers_dst) plt.ylim(fingers_dst[0], fingers_dst[-1]) plt.ylabel("To finger", fontsize=15) plt.title("Difficulty of finger passages", fontsize=25) plt.savefig('./figures/image.png', figsize=(16, 12), dpi=300) plt.show()
def hexbin_plot(self, var1, var2, force=False): fig_name = "{}/hexbin_{}_{}.pdf".format(self.fig_folder, var1, var2) if path.exists(fig_name) and not force: return if var1 == "customer_extra_view_choices" and var2 == "delta_position": print("Doing hexbin plot '{}' against '{}'.".format(var2, var1)) x = np.asarray(self.stats.data[var1]) y = np.asarray(self.stats.data[var2]) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.xlim(self.range_var[var1]) plt.ylim(self.range_var[var2]) plt.xlabel(self.format_label(var1)) plt.ylabel(self.format_label(var2)) hb = ax.hexbin(x=x, y=y, gridsize=20, cmap='inferno') ax.set_facecolor('black') cb = fig.colorbar(hb, ax=ax) cb.set_label('counts') plt.savefig(fig_name) if self.display: plt.show() plt.close()
def test_plot_dep_contour(self): plot = MapPlotSlab() plot.plot_dep_contour(-20, color='red') plot.plot_dep_contour(-40, color='blue') plot.plot_dep_contour(-60, color='black') plt.savefig(join(this_test_path, '~outs/plot_dep_contour.png')) plt.close()
def serve_css(name, length, keys, values): from pylab import plt, mpl mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False from matplotlib.font_manager import FontProperties # font = FontProperties(fname="d:\Users\ll.tong\Desktop\msyh.ttf", size=12) font = FontProperties(fname="/usr/share/fonts/msyh.ttf", size=11) plt.xlabel(u'') plt.ylabel(u'出现次数',fontproperties=font) plt.title(u'词频统计',fontproperties=font) plt.grid() keys = keys.decode("utf-8").split(' ') values = values.split(' ') valuesInt = [] for value in values: valuesInt.append(int(value)) plt.xticks(range(int(length)), keys) plt.plot(range(int(length)), valuesInt) plt.xticks(rotation=defaultrotation, fontsize=9,fontproperties=font) plt.yticks(fontsize=10,fontproperties=font) name = name + str(datetime.now().date()).replace(':', '') + '.png' imgUrl = 'static/temp/' + name fig = matplotlib.pyplot.gcf() fig.set_size_inches(12.2, 2) plt.savefig(imgUrl, bbox_inches='tight', figsize=(20,4), dpi=100) plt.close() tempfile = static_file(name, root='./static/temp/') #os.remove(imgUrl) return tempfile
def hexbin_plot(self, var1, var2): print("Doing hexbin plot '{}' against '{}'.".format(var2, var1)) x = np.asarray(self.stats.data[var1]) y = np.asarray(self.stats.data[var2]) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.xlim(self.range_var[var1]) plt.ylim(self.range_var[var2]) plt.xlabel(self.format_label(var1)) plt.ylabel(self.format_label(var2)) hb = ax.hexbin(x=x, y=y, gridsize=20, cmap='inferno') ax.set_facecolor('black') cb = fig.colorbar(hb, ax=ax) cb.set_label('counts') plt.savefig("{}/hexbin_{}_{}.pdf".format(self.fig_folder, var1, var2)) if self.display: plt.show() plt.close()
def main(data_folder="../data", figure_folder="../figures"): deviation_from_equilibrium = dict() for i in [(1, 0), (2, 0), (2, 1)]: deviation_from_equilibrium[i] = \ json.load(open("{}/deviation_from_equilibrium_{}.json".format(data_folder, i), mode="r")) x = np.arange(len(list(deviation_from_equilibrium.values())[0])) fig, ax = plt.subplots() for i in deviation_from_equilibrium.keys(): ax.plot(x, deviation_from_equilibrium[i], label='{} against {}'.format(i[0], i[1])) ax.legend(fontsize=12) # loc='upper center ax.set_xlabel("generation") ax.set_ylabel("actual price / equilibrium price") ax.set_title( "Price Dynamics in Scarf Three-good Economy \n(relative deviation from equilibrium prices)" ) if not path.exists(figure_folder): mkdir(figure_folder) plt.savefig("{}/figure.pdf".format(figure_folder)) plt.show()
def plot(cls, data, figure_folder, msg="", suffix=""): fig, ax = plt.subplots() plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2) x = np.arange(len(data[:])) ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01") ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12") ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20") plt.ylim([-0.01, 1.01]) plt.text(0, -0.23, "PARAMETERS. {}".format(msg)) ax.legend(fontsize=12, bbox_to_anchor=(1.1, 1.05)) # loc='upper center' ax.set_xlabel("$t$") ax.set_ylabel("Proportion of agents proceeding to indirect exchange") ax.set_title("Money emergence with a basal ganglia model") # Save fig if not exists(figure_folder): mkdir(figure_folder) fig_name = "{}/figure_{}.pdf".format(figure_folder, suffix.split(".p")[0]) plt.savefig(fig_name) plt.close()
def pure_data_plot(self,connect=False,suffix='',cmap=cm.jet,bg=cm.bone(0.3)): #fig=plt.figure() ax=plt.axes() plt.axhline(y=0,color='grey', zorder=-1) plt.axvline(x=0,color='grey', zorder=-2) if cmap is None: if connect: ax.plot(self.x,self.y, 'b-',lw=2,alpha=0.5) ax.scatter(self.x,self.y, marker='o', c='b', s=40) else: if connect: if cmap in [cm.jet,cm.brg]: ax.plot(self.x,self.y, 'c-',lw=2,alpha=0.5,zorder=-1) else: ax.plot(self.x,self.y, 'b-',lw=2,alpha=0.5) c=[cmap((f-self.f[0])/(self.f[-1]-self.f[0])) for f in self.f] #c=self.f ax.scatter(self.x, self.y, marker='o', c=c, edgecolors=c, zorder=True, s=40) #, cmap=cmap) #plt.axis('equal') ax.set_xlim(xmin=-0.2*amax(self.x), xmax=1.2*amax(self.x)) ax.set_aspect('equal') #, 'datalim') if cmap in [cm.jet,cm.brg]: ax.set_axis_bgcolor(bg) if self.ZorY == 'Z': plt.xlabel(r'resistance $R$ in Ohm'); plt.ylabel(r'reactance $X$ in Ohm') if self.ZorY == 'Y': plt.xlabel(r'conductance $G$ in Siemens'); plt.ylabel(r'susceptance $B$ in Siemens') if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'c{}_{}_circle_data'.format(self.sdc.case,self.ZorY)+self.sdc.suffix+self.sdc.outsuffix+suffix+'.png'), dpi=240) plt.close()
def plot_stat(rows, cache): "Use matplotlib to plot DAS statistics" if not PLOT_ALLOWED: raise Exception('Matplotlib is not available on the system') if cache in ['cache', 'merge']: # cachein, cacheout, mergein, mergeout name_in = '%sin' % cache name_out = '%sout' % cache else: # webip, webq, cliip, cliq name_in = '%sip' % cache name_out = '%sq' % cache def format_date(date): "Format given date" val = str(date) return '%s-%s-%s' % (val[:4], val[4:6], val[6:8]) date_range = [r['date'] for r in rows] formated_dates = [format_date(str(r['date'])) for r in rows] req_in = [r[name_in] for r in rows] req_out = [r[name_out] for r in rows] plt.plot(date_range, req_in , 'ro-', date_range, req_out, 'gv-', ) plt.grid(True) plt.axis([min(date_range), max(date_range), \ 0, max([max(req_in), max(req_out)])]) plt.xticks(date_range, tuple(formated_dates), rotation=17) # plt.xlabel('dates [%s, %s]' % (date_range[0], date_range[-1])) plt.ylabel('DAS %s behavior' % cache) plt.savefig('das_%s.pdf' % cache, format='pdf', transparent=True) plt.close()
def link_level_bars(levels, usages, quantiles, scheme, direction, color, nnames, lnames, admat=None): """ Bar plots of nodes' link usage of links at different levels. """ if not admat: admat = np.genfromtxt('./settings/eadmat.txt') if color == 'solar': cmap = Oranges_cmap elif color == 'wind': cmap = Blues_cmap elif color == 'backup': cmap = 'Greys' nodes, links = usages.shape usageLevels = np.zeros((nodes, levels)) usageLevelsNorm = np.zeros((nodes, levels)) for node in range(nodes): nl = neighbor_levels(node, levels, admat) for lvl in range(levels): ll = link_level(nl, lvl, nnames, lnames) ll = np.array(ll, dtype='int') usageSum = sum(usages[node, ll]) linkSum = sum(quantiles[ll]) usageLevels[node, lvl] = usageSum / linkSum if lvl == 0: usageLevelsNorm[node, lvl] = usageSum else: usageLevelsNorm[node, lvl] = usageSum / usageLevelsNorm[node, 0] usageLevelsNorm[:, 0] = 1 # plot all nodes usages = usageLevels.transpose() plt.figure(figsize=(11, 3)) ax = plt.subplot() plt.pcolormesh(usages[:, loadOrder], cmap=cmap) plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11) ax.set_yticks(np.linspace(.5, levels - .5, levels)) ax.set_yticklabels(range(1, levels + 1)) ax.yaxis.set_tick_params(width=0) ax.xaxis.set_tick_params(width=0) ax.set_xticks(np.linspace(1, nodes, nodes)) ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10) plt.ylabel('Link level') plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total' + '_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight') plt.close() # plot all nodes normalised to usage of first level usages = usageLevelsNorm.transpose() plt.figure(figsize=(11, 3)) ax = plt.subplot() plt.pcolormesh(usages[:, loadOrder], cmap=cmap) plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11) ax.set_yticks(np.linspace(.5, levels - .5, levels)) ax.set_yticklabels(range(1, levels + 1)) ax.yaxis.set_tick_params(width=0) ax.xaxis.set_tick_params(width=0) ax.set_xticks(np.linspace(1, nodes, nodes)) ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10) plt.ylabel('Link level') plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total_norm_cont_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight') plt.close()
def plot_inv_conv(fvals, name, direc): plt.figure() plt.semilogy(fvals, 'ko-') plt.xlabel('Iterations') plt.ylabel('Cost Function') plt.savefig(os.path.join(direc, name + '.png'), dpi=300) plt.close()
def curve_plot(self, variable, t_max): print("Doing curve plot for variable '{}'.".format(variable)) var = Variable(name=variable) if var.data is None: self.extract_single_dimension(var, t_max=t_max) x = np.arange(t_max) mean = var.data["mean"] std = var.data["std"] plt.plot(x, mean, c='black', lw=2) plt.plot(x, mean + std, c='black', lw=.1) plt.plot(x, mean - std, c='black', lw=.1) plt.fill_between(x, mean + std, mean - std, color='black', alpha=.1) plt.xlabel("t") plt.ylabel(self.format_label(variable)) plt.savefig("{}/curve_plot_{}.pdf".format(self.fig_folder, variable)) if self.display: plt.show() plt.close()
def plot_profits(self, player, period): profits = self.results["profits"][-period:] plt.title("Profits") time_window = 100 x = np.arange(len(profits[:, player])) y = [] for i in x: if i < time_window: y_value = np.mean(profits[:i + 1, player]) else: y_value = np.mean(profits[i - time_window:i + 1, player]) y.append(y_value) plt.plot(x, y, color="black") maximum_profit = \ self.parameters["n_positions"] * \ self.parameters["n_prices"] plt.ylim(0, maximum_profit) plt.annotate("Time window: {}".format(time_window), xy=(0.8, 0.1), xycoords='axes fraction', fontsize=6) # plt.annotate(self.string_parameters, xy=(-0.05, -0.1), xycoords='axes fraction', fontsize=6) plt.savefig(self.format_fig_name("profits_player{}".format(player))) plt.close()
def plot_response(data, plate_name, save_folder = 'Figures/'): """ """ if not os.path.isdir(save_folder): os.makedirs(save_folder) for block in data: # group = group_similar(data[block].keys()) names = data[block].keys() names.sort() # plt.figure(figsize=(16, 4 + len(names)/8), dpi=300) # for i, name in enumerate(names): a, b, c = get_index(group, name) color, pattern = color_shade_pattern(a, b, c, group) mean = data[block][name]['mean'][0] std = data[block][name]['std'][0] plt.barh([i], [mean], height=1.0, color=color, hatch=pattern) plt.errorbar([mean], [i+0.5], xerr=[std], ecolor = [0,0,0], linestyle = '') plt.yticks([i+0.5 for i in xrange(len(names))], names, size = 8) plt.title(plate_name) plt.ylim(0, len(names)) plt.xlabel('change') plt.tight_layout() plt.savefig(save_folder + 'response_' + str(block + 1)) # return None
def prices_and_profits(pool_backup, fig_name=None, ax_price=None, ax_profit=None): # Create figure and axes if not given in args if ax_price is None or ax_profit is None: fig = plt.figure(figsize=(4, 5), dpi=200) n_rows = 2 n_cols = 1 ax_price = fig.add_subplot(n_rows, n_cols, 1) ax_profit = fig.add_subplot(n_rows, n_cols, 2) prices_over_fov(pool_backup, ax_price) profits_over_fov(pool_backup, ax_profit) if fig_name is not None: # Cut margins plt.tight_layout() # Create directories if not already existing os.makedirs(os.path.dirname(fig_name), exist_ok=True) # Save fig plt.savefig(fig_name) plt.close()
def draw(cls, t_max, agents_proportions, eco_idx, parameters): color_set = ["green", "blue", "red"] for agent_type in range(3): plt.plot(np.arange(t_max), agents_proportions[:, agent_type], color=color_set[agent_type], linewidth=2.0, label="Type-{} agents".format(agent_type)) plt.ylim([-0.1, 1.1]) plt.xlabel("$t$") plt.ylabel("Proportion of indirect exchanges") # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold') plt.legend(loc='upper right', fontsize=12) print(parameters) plt.title( "Workforce: {}, {}, {}; displacement area: {}; vision area: {}; alpha: {}; tau: {}\n" .format( parameters["x0"], parameters["x1"], parameters["x2"], parameters["movement_area"], parameters["vision_area"], parameters["alpha"], parameters["tau"] ), fontsize=12) if not path.exists("../../figures"): mkdir("../../figures") plt.savefig("../../figures/figure_{}.pdf".format(eco_idx)) plt.show()
def draw_plot(company_name, hyper_parameter, plot_data): point_list = ['C0o-', 'C1o-', 'C2o-', 'C3o-', 'C4o-', 'C5o-'] x = np.arange(len(plot_data[0][1])) x_label = np.zeros(len(plot_data[0][1])) for i, val in enumerate(plot_data[0][1]): x_label[i] = val[0] fig, ax = plt.subplots(1, 1) for j, model in enumerate(plot_data): model_name = model[0] y = np.zeros(len(model[1])) for i, val in enumerate(model[1]): y[i] = val[1] ax.plot(x, y, point_list[j], label=model_name) ax.set_title(company_name + "'s MSE results w/ " + hyper_parameter, fontdict={ 'fontsize': 18, 'weight': 'bold' }) ax.set_ylabel('MSE', fontdict={'fontsize': 15, 'weight': 'bold'}) ax.set_xlabel(hyper_parameter, fontdict={'fontsize': 15, 'weight': 'bold'}) ax.set_xticks(x) ax.set_xticklabels(x_label) ax.legend() dir_path = 'MSE_figures\\' + company_name os.system('mkdir ' + dir_path) plt.savefig(dir_path + '\\' + company_name + '_' + hyper_parameter + '.png')
def create_image(csv_path): csv_data, _, _ = read_csv_data(csv_path) plt.figure() plt.plot(csv_data) plt.axis('off') plt.savefig('wind_data.png', bbox_inches='tight', dpi=500)
def draw(cls, t_max, agents_proportions, eco_idx, parameters): color_set = ["green", "blue", "red"] for agent_type in range(3): plt.plot(np.arange(t_max), agents_proportions[:, agent_type], color=color_set[agent_type], linewidth=2.0, label="Type-{} agents".format(agent_type)) plt.ylim([-0.1, 1.1]) plt.xlabel("$t$") plt.ylabel("Proportion of indirect exchanges") # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold') plt.legend(loc='upper right', fontsize=12) print(parameters) plt.title( "Workforce: {}, {}, {}; displacement area: {}; vision area: {}; alpha: {}; tau: {}\n" .format(parameters["x0"], parameters["x1"], parameters["x2"], parameters["movement_area"], parameters["vision_area"], parameters["alpha"], parameters["tau"]), fontsize=12) if not path.exists("../../figures"): mkdir("../../figures") plt.savefig("../../figures/figure_{}.pdf".format(eco_idx)) plt.show()
def phase_diagram(data, labels, n_good, title=None, ax=None, letter=None, n_ticks=3, fig_name=None): if ax is None: print('No ax given, I will create a fig.') fig, ax = plt.subplots() im = ax.imshow(data, cmap="binary", origin="lower", vmin=0.2, vmax=0.8) # , vmin=0.5) # Create colorbar cbar = ax.figure.colorbar(im, ax=ax) step = int(len(labels) / n_ticks) lab_to_display = labels[::step] ax.set_xticklabels(lab_to_display) ax.set_yticklabels(lab_to_display) ticks = list(range(len(labels)))[::step] ax.set_xticks(ticks) ax.set_yticks(ticks) ax.tick_params(labelsize=8) ax.set_xlabel(f'$x_{n_good-2}$') ax.set_ylabel(f'$x_{n_good-1}$') ax.set_aspect(1) if title is not None: ax.set_title(title) if letter: ax.text(s=letter, x=-0.1, y=-0.2, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=20) if 'fig' in locals(): print('Saving fig.') # noinspection PyUnboundLocalVariable fig.tight_layout() if fig_name is None: fig_name = f'fig/phase_{n_good}.pdf' os.makedirs(os.path.dirname(fig_name), exist_ok=True) plt.savefig(fig_name)
def generate_start_time_figures(self): recording_time_grouped_by_patient = self.pain_data[["PatientID", "NRSTimeFromEndSurgery_mins"]].groupby("PatientID") recording_start_minutes = recording_time_grouped_by_patient.min() fig1 = "fig1.pdf" fig2 = "fig2.pdf" plt.figure(figsize=[8,4]) plt.title("Pain score recording start times", fontsize=14).set_y(1.05) plt.ylabel("Occurrences", fontsize=14) plt.xlabel("Recording Start Time (minutes)", fontsize=14) plt.hist(recording_start_minutes.values, bins=20, color="0.5") plt.savefig(os.path.join(self.tmp_directory, fig1), bbox_inches="tight") plt.figure(figsize=[8,4]) plt.title("Pain score recording start times, log scale", fontsize=14).set_y(1.05) plt.ylabel("Occurrences", fontsize=14) plt.xlabel("Recording Start Time (minutes)", fontsize=14) plt.hist(recording_start_minutes.values, bins=20, log=True, color="0.5") plt.savefig(os.path.join(self.tmp_directory, fig2), bbox_inches="tight") #save the figures in panel format f = open(os.path.join(self.tmp_directory, "tmp.tex"), 'w') f.write(r""" \documentclass[% ,float=false % this is the new default and can be left away. ,preview=true ,class=scrartcl ,fontsize=20pt ]{standalone} \usepackage[active,tightpage]{preview} \usepackage{varwidth} \usepackage{graphicx} \usepackage[justification=centering]{caption} \usepackage{subcaption} \usepackage[caption=false,font=footnotesize]{subfig} \renewcommand{\thesubfigure}{\Alph{subfigure}} \begin{document} \begin{preview} \begin{figure}[h] \begin{subfigure}{0.5\textwidth} \includegraphics[width=\textwidth]{""" + fig1 + r"""} \caption{Normal scale} \end{subfigure}\begin{subfigure}{0.5\textwidth} \includegraphics[width=\textwidth]{""" + fig2 + r"""} \caption{Log scale} \end{subfigure} \end{figure} \end{preview} \end{document} """) f.close() subprocess.call(["pdflatex", "-halt-on-error", "-output-directory", self.tmp_directory, os.path.join(self.tmp_directory, "tmp.tex")]) shutil.move(os.path.join(self.tmp_directory, "tmp.pdf"), os.path.join(self.output_directory, "pain_score_start_times.pdf"))
def save_images(images, path): fig = plt.figure() for i, image in enumerate(images): fig.add_subplot(1, len(images), i + 1) plt.imshow(image) plt.axis('off') plt.savefig(path, bbox_inches='tight') plt.close()
def test_plot_slip(self): ep = EpochalIncrSlip(self.file_incr_slip) plot = MapPlotFault(self.file_fault) plot.plot_slip(ep(0)) plt.savefig(join(self.outs_dir, 'plot_slip.png')) plt.close()
def test_plot(self): res_file = '/home/zy/workspace/viscojapan/tests/share/nrough_05_naslip_11.h5' reader = vj.inv.ResultFileReader(res_file) slip = reader.get_slip() plotter = vj.slip.plot.plot_slip_and_rate_at_subflt(slip, 8, 8) plt.savefig(join(self.outs_dir, 'slip_and_rate.pdf'))
def plot_data(self): for i,dat in enumerate(self.data): plt.imshow(dat, cmap=cm.jet, interpolation=None, extent=[11,22,-3,2]) txt='plot '.format(self.n[i]) txt+='\nmin {0:.2f} und max {1:.2f}'.format(self.min[i],self.max[i]) txt+='\navg. min {0:.2f} und avg. max {1:.2f}'.format(mean(self.min),mean(self.max)) plt.suptitle(txt,x=0.5,y=0.98,ha='center',va='top',fontsize=10) plt.savefig(join(self.plotpath,'pic_oo_'+str(self.n[i])+'.png')) plt.close() # wichtig, sonst wird in den selben Plot immer mehr reingepackt
def test_plot(self): res_file = '/home/zy/workspace/viscojapan/tests/share/nrough_05_naslip_11.h5' reader = vj.inv.ResultFileReader(res_file) slip = reader.get_slip() plotter = vj.slip.plot.plot_slip_and_rate_at_subflt( slip, 8, 8) plt.savefig(join(self.outs_dir, 'slip_and_rate.pdf'))
def plot_bw(ax, x, y, file_name, fig_folder): ax.scatter(x, y, facecolor="black", edgecolor='none', s=25, alpha=0.15) plt.tight_layout() if file_name: plt.savefig("{}/{}_gray.pdf".format(fig_folder, file_name)) plt.show()
def test_dip(self): xf = arange(0, 425) dips = self.fm.get_dip(xf) plt.plot(xf,dips) plt.grid('on') plt.gca().set_xticks(self.fm.Y_PC) plt.ylim([0, 30]) plt.gca().invert_yaxis() plt.savefig(join(self.outs_dir, '~y_fc_dips.png')) plt.close()
def plot_mat(self, mat, fn): plt.matshow(asarray(mat.todense())) plt.axis('equal') sh = mat.shape plt.gca().set_yticks(range(0,sh[0])) plt.gca().set_xticks(range(0,sh[1])) plt.grid('on') plt.colorbar() plt.savefig(join(self.outs_dir, fn)) plt.close()
def plot_mat(self, mat, fn): plt.matshow(asarray(mat.todense())) plt.axis('equal') sh = mat.shape plt.gca().set_yticks(range(0, sh[0])) plt.gca().set_xticks(range(0, sh[1])) plt.grid('on') plt.colorbar() plt.savefig(join(self.outs_dir, fn)) plt.close()
def plot_post(cfs,ifshow=False,loc=2, save_fig_path = None, file_type='png'): for cf in cfs: plot_cf(cf, color='blue') plt.legend(loc=loc) if ifshow: plt.show() if save_fig_path is not None: plt.savefig(join(save_fig_path, '%s_%s.%s'%(cf.SITE, cf.CMPT, file_type))) plt.close()
def test_dip(self): xf = arange(0, 425) dips = self.fm.get_dip(xf) plt.plot(xf, dips) plt.grid('on') plt.gca().set_xticks(self.fm.Y_PC) plt.ylim([0, 30]) plt.gca().invert_yaxis() plt.savefig(join(self.outs_dir, '~y_fc_dips.png')) plt.close()
def plot_iou(checkpoint_dir, iou_list): x = range(0, len(iou_list)) y = iou_list plt.switch_backend('agg') plt.plot(x, y, color='red', marker='o', label='IOU') plt.xticks(range(0, len(iou_list) + 3, (len(iou_list) + 10) // 10)) plt.legend() plt.grid() plt.savefig(os.path.join(checkpoint_dir, 'iou_fig.pdf')) plt.close()
def plot_loss(checkpoint_dir, loss_list, save_pred_every): x = range(0, len(loss_list) * save_pred_every, save_pred_every) y = loss_list plt.switch_backend('agg') plt.plot(x, y, color='blue', marker='o', label='Train loss') plt.xticks(range(0, len(loss_list) * save_pred_every + 3, (len(loss_list) * save_pred_every + 10) // 10)) plt.legend() plt.grid() plt.savefig(os.path.join(checkpoint_dir, 'loss_fig.pdf')) plt.close()
def plotSigmoidTanh(fname=None): fig, ax = plt.subplots() xs = np.linspace(-10.0, 10.0, num = 50, endpoint=True) ys = [sigmoidTanh(x, 0.9) for x in xs] ax.plot(xs, ys, 'black') plt.title("y=sigmoid(s)") plt.grid(True) if fname: plt.savefig(fname) plt.show()
def test_pcolor_on_fault(self): ep = EpochalIncrSlip(self.file_incr_slip) fio = FaultFileIO(self.file_fault) slip = ep(0).reshape( [fio.num_subflt_along_dip, fio.num_subflt_along_strike]) plot = MapPlotFault(self.file_fault) plot.pcolor_on_fault(slip) plt.savefig(join(self.outs_dir, 'pcolor_on_fault.png')) plt.close()
def drawHeatMap(dataDF, groupByVariableNames, subplotIndex, subplotIndexName, valueIndexName): figure = plt.figure(figsize=(12, 10)) order = [7,8,9,4,5,6,1,2,3] numOfplot = 0 for key, subDF in dataDF.groupby(groupByVariableNames): subplot = figure.add_subplot(subplotIndex[0], subplotIndex[1], order[numOfplot]) plotDF = subDF.reset_index() plotDF.plot.scatter(x=subplotIndexName[0], y=subplotIndexName[1], c=valueIndexName, colormap="jet", ax=subplot, vmin=0, vmax=9) numOfplot = numOfplot + 1 plt.subplots_adjust(wspace=0.8, hspace=0.4) plt.savefig("./Graphs/Factor3_fixed_50sample_actionDistribution_divergence_HeatMap.png")
def plot_color(fig, ax, x, y, z, file_name, fig_folder): abc = ax.scatter(x, y, c=z, zorder=10, alpha=0.25) fig.colorbar(abc, label="Profits") plt.tight_layout() if file_name: plt.savefig("{}/{}.pdf".format(fig_folder, file_name)) plt.show()
def convert_all_to_png(vis_path, out_dir="maps_png", size=None): units = { 'gas_density': 'Gas Density [g/cm$^3$]', 'Tm': 'Temperature [K]', 'Tew': 'Temperature [K]', 'S': 'Entropy []', 'dm': 'DM Density [g/cm$^3$]', 'v': 'Velocity [km/s]' } log_list = ['gas_density'] for vis_file in os.listdir(vis_path): if ".dat" not in vis_file: continue print "converting %s" % vis_file map_type = re.search('sigma_(.*)_[xyz]', vis_file).group(1) (image, pixel_size, axis_values) = read_visualization_data(vis_path + "/" + vis_file, size) print "image width in Mpc/h: ", axis_values[-1] * 2.0 x, y = np.meshgrid(axis_values, axis_values) cmap_max = image.max() cmap_min = image.min() ''' plotting ''' plt.figure(figsize=(5, 4)) if map_type in log_list: plt.pcolor(x, y, image, norm=LogNorm(vmax=cmap_max, vmin=cmap_min)) else: plt.pcolor(x, y, image, vmax=cmap_max, vmin=cmap_min) cbar = plt.colorbar() if map_type in units.keys(): cbar.ax.set_ylabel(units[map_type]) plt.axis( [axis_values[0], axis_values[-1], axis_values[0], axis_values[-1]]) del image plt.xlabel(r"$Mpc/h$", fontsize=18) plt.ylabel(r"$Mpc/h$", fontsize=18) out_file = vis_file.replace("dat", "png") plt.savefig(out_dir + "/" + out_file, dpi=150) plt.close() plt.clf()
def savefig(self, fname): # Graph using the parameters plt.xlim(-1000, max(self.incomes) * 1.05) # make it a little bigger than needed plt.ylim(-5, 105) plt.legend(loc='lower center', fontsize=9) plt.xticks(rotation=20) plt.axes().get_xaxis().set_major_formatter( mp.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) plt.savefig(fname)
def test_pcolor_on_fault(self): ep = EpochalIncrSlip(self.file_incr_slip) fio = FaultFileIO(self.file_fault) slip = ep(0).reshape([fio.num_subflt_along_dip, fio.num_subflt_along_strike]) plot = MapPlotFault(self.file_fault) plot.pcolor_on_fault(slip) plt.savefig(join(self.outs_dir, 'pcolor_on_fault.png')) plt.close()
def test_share_basemap(self): bm = MyBasemap(x_interval = 1) p1 = MapPlotSlab(basemap = bm) p1.plot_top() p2 = MapPlotFault(fault_file=join(this_script_dir, 'share/fault.h5'), basemap = bm) p2.plot_fault() plt.savefig(join(this_script_dir, '~outs/share_basemap.png')) plt.close()
def test_fault2geo(self): xf = linspace(0., 700, 25) yf = linspace(0, 425, 30) xxf, yyf = meshgrid(xf, yf) LLons, LLats = self.fm.fault2geo(xxf, yyf) self.plt_map.basemap.plot(LLons,LLats,color='gray',latlon=True) self.plt_map.basemap.plot(ascontiguousarray(LLons.T), ascontiguousarray(LLats.T), color='gray',latlon=True) plt.savefig('~test_fault2geo.png') plt.close()
def plot_smoothed_alpha_comparison(self,rmsval,suffix=''): plt.plot(self.f,self.alpha,'ko',label='data set') plt.plot(self.f,self.salpha,'c-',lw=2,label='smoothed angle $\phi$') plt.xlabel('frequency in Hz') plt.ylabel('angle $\phi$ in coordinates of circle') plt.legend() ylims=plt.axes().get_ylim() plt.yticks((arange(9)-4)*0.5*pi, ['$-2\pi$','$-3\pi/2$','$-\pi$','$-\pi/2$','$0$','$\pi/2$','$\pi$','$3\pi/2$','$2\pi$']) plt.ylim(ylims) plt.title('RMS offset from smooth curve: {:.4f}'.format(rmsval)) if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'salpha','c{}_salpha_on_{}_circle'.format(self.sdc.case,self.ZorY)+self.sdc.suffix+self.sdc.outsuffix+suffix+'.png'), dpi=240) plt.close()
def test_ground2geo(self): xp = linspace(0, 700, 25) yp = linspace(0, 425, 30) xxp, yyp = meshgrid(xp, yp) LLons, LLats = self.fm.ground2geo(xxp, yyp) self.plt_map.basemap.plot(LLons,LLats,color='gray',latlon=True) self.plt_map.basemap.plot(ascontiguousarray(LLons.T), ascontiguousarray(LLats.T), color='gray',latlon=True) plt.savefig('~test_ground2geo.png') plt.close()
def convert_all_to_png(vis_path, out_dir = "maps_png", size = None) : units = { 'gas_density' : 'Gas Density [g/cm$^3$]', 'Tm' : 'Temperature [K]', 'Tew' : 'Temperature [K]', 'S' : 'Entropy []', 'dm' : 'DM Density [g/cm$^3$]', 'v' : 'Velocity [km/s]' } log_list = ['gas_density'] for vis_file in os.listdir(vis_path) : if ".dat" not in vis_file : continue print "converting %s" % vis_file map_type = re.search('sigma_(.*)_[xyz]', vis_file).group(1) (image, pixel_size, axis_values) = read_visualization_data(vis_path+"/"+vis_file, size) print "image width in Mpc/h: ", axis_values[-1]*2.0 x, y = np.meshgrid( axis_values, axis_values ) cmap_max = image.max() cmap_min = image.min() ''' plotting ''' plt.figure(figsize=(5,4)) if map_type in log_list: plt.pcolor(x,y,image, norm=LogNorm(vmax=cmap_max, vmin=cmap_min)) else : plt.pcolor(x,y,image, vmax=cmap_max, vmin=cmap_min) cbar = plt.colorbar() if map_type in units.keys() : cbar.ax.set_ylabel(units[map_type]) plt.axis([axis_values[0], axis_values[-1],axis_values[0], axis_values[-1]]) del image plt.xlabel(r"$Mpc/h$", fontsize=18) plt.ylabel(r"$Mpc/h$", fontsize=18) out_file = vis_file.replace("dat", "png") plt.savefig(out_dir+"/"+out_file, dpi=150 ) plt.close() plt.clf()
def plot_overview_B(self,suffix='',ansize=8,anspread=0.15,anmode='quarters',datbg=True,datbgsource=None,checkring=False): self.start_plot() if datbg: # data background desired self.plot_bg_data(datbgsource=datbgsource) #self.plot_data() self.plot_fitcircle() if checkring: self.plot_checkring() idxlist=self.to_be_annotated(anmode) self.annotate_data_points(idxlist,ansize,anspread) self.plot_characteristic_freqs(annotate=True,size=ansize,spread=anspread) if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'c{}_fitted_{}_circle'.format(self.sdc.case,self.ZorY)+self.sdc.suffix+self.sdc.outsuffix+suffix+'.png'), dpi=240) plt.close()
def main(args=sys.argv[1:]): # there are some cases when this script is run on systems without DISPLAY variable being set # in such case matplotlib backend has to be explicitly specified # we do it here and not in the top of the file, as inteleaving imports with code lines is discouraged import matplotlib matplotlib.use('Agg') from pylab import plt, ylabel, grid, xlabel, array parser = argparse.ArgumentParser() parser.add_argument("rst_file", help="location of rst file in TRiP98 format", type=str) parser.add_argument("output_file", help="location of PNG file to save", type=str) parser.add_argument("-s", "--submachine", help="Select submachine to plot.", type=int, default=1) parser.add_argument("-f", "--factor", help="Factor for scaling the blobs. Default is 1000.", type=int, default=1000) parser.add_argument("-v", "--verbosity", action='count', help="increase output verbosity", default=0) parser.add_argument('-V', '--version', action='version', version=pt.__version__) args = parser.parse_args(args) file = args.rst_file sm = args.submachine fac = args.factor a = pt.Rst() a.read(file) # convert data in submachine to a nice array b = a.machines[sm] x = [] y = [] z = [] for _x, _y, _z in b.raster_points: x.append(_x) y.append(_y) z.append(_z) title = "Submachine: {:d} / {:d} - Energy: {:.3f} MeV/u".format(sm, len(a.machines), b.energy) print(title) cc = array(z) cc = cc / cc.max() * fac fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(x, y, c=cc, s=cc, alpha=0.75) ylabel("mm") xlabel("mm") grid(True) plt.title(title) plt.savefig(args.output_file) plt.close()
def draw(cls, t_max, agents_proportions, suffix): color_set = ["green", "blue", "red"] for agent_type in range(3): plt.plot(np.arange(t_max), agents_proportions[:, agent_type], color=color_set[agent_type], linewidth=1.0) plt.ylim([0, 1]) # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold') # plt.legend(loc='lower left', frameon=False) plt.savefig("figure_{}.pdf".format(suffix))
def drawAdoptionNetworkMPL(G, fnum=1, show=False, writeFile=None): """Draws the network to matplotlib, coloring the nodes based on adoption. Looks for the node attribute 'adopted'. If the attribute is True, colors the node a different color, showing adoption visually. This function assumes that the node attributes have been pre-populated. :param networkx.Graph G: Any NetworkX Graph object. :param int fnum: The matplotlib figure number. Defaults to 1. :param bool show: :param str writeFile: A filename/path to save the figure image. If not specified, no output file is written. """ Gclean = G.subgraph([n for n in G.nodes() if n not in nx.isolates(G)]) plt.figure(num=fnum, figsize=(6,6)) # clear figure plt.clf() # Blue ('b') node color for adopters, red ('r') for non-adopters. nodecolors = ['b' if Gclean.node[n]['adopted'] else 'r' \ for n in Gclean.nodes()] layout = nx.spring_layout(Gclean) nx.draw_networkx_nodes(Gclean, layout, node_size=80, nodelist=Gclean.nodes(), node_color=nodecolors) nx.draw_networkx_edges(Gclean, layout, alpha=0.5) # width=4 # TODO: Draw labels of Ii values. Maybe vary size of node. # TODO: Color edges blue based on influences from neighbors influenceEdges = [] for a in Gclean.nodes(): for n in Gclean.node[a]['influence']: influenceEdges.append((a,n)) if len(influenceEdges)>0: nx.draw_networkx_edges(Gclean, layout, alpha=0.5, width=5, edgelist=influenceEdges, edge_color=['b']*len(influenceEdges)) #some extra space around figure plt.xlim(-0.05,1.05) plt.ylim(-0.05,1.05) plt.axis('off') if writeFile != None: plt.savefig(writeFile) if show: plt.show()
def plot_overview(self,suffix=''): x=self.x; y=self.y; r=self.radius; cx,cy=self.center.real,self.center.imag ax=plt.axes() plt.scatter(x,y, marker='o', c='b', s=40) plt.axhline(y=0,color='grey', zorder=-1) plt.axvline(x=0,color='grey', zorder=-2) t=linspace(0,2*pi,201) circx=r*cos(t) + cx circy=r*sin(t) + cy plt.plot(circx,circy,'g-') plt.plot([cx],[cy],'gx',ms=12) if self.ZorY == 'Z': philist,flist=[self.phi_a,self.phi_p,self.phi_n],[self.fa,self.fp,self.fn] elif self.ZorY == 'Y': philist,flist=[self.phi_m,self.phi_s,self.phi_r],[self.fm,self.fs,self.fr] for p,f in zip(philist,flist): if f is not None: xpos=cx+r*cos(p); ypos=cy+r*sin(p); xos=0.2*(xpos-cx); yos=0.2*(ypos-cy) plt.plot([0,xpos],[0,ypos],'co-') ax.annotate('{:.3f} Hz'.format(f), xy=(xpos,ypos), xycoords='data', xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points', arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10) ) #plt.xlim(0,0.16) #plt.ylim(-0.1,0.1) plt.axis('equal') if self.ZorY == 'Z': plt.xlabel(r'resistance $R$ in Ohm'); plt.ylabel(r'reactance $X$ in Ohm') if self.ZorY == 'Y': plt.xlabel(r'conductance $G$ in Siemens'); plt.ylabel(r'susceptance $B$ in Siemens') plt.title("fitting the admittance circle with Powell's method") tx1='best fit (fmin_powell):\n' tx1+='center at G+iB = {:.5f} + i*{:.8f}\n'.format(cx,cy) tx1+='radius = {:.5f}; '.format(r) tx1+='residue: {:.2e}'.format(self.resid) txt1=plt.text(-r,cy-1.1*r,tx1,fontsize=8,ha='left',va='top') txt1.set_bbox(dict(facecolor='gray', alpha=0.25)) idxlist=self.to_be_annotated('triple') ofs=self.annotation_offsets(idxlist,factor=0.1,xshift=0.15) for i,j in enumerate(idxlist): xpos,ypos = x[j],y[j]; xos,yos = ofs[i].real,ofs[i].imag ax.annotate('{:.1f} Hz'.format(self.f[j]), xy=(xpos,ypos), xycoords='data', xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points', arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10) ) if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'c{}_fitted_{}_circle'.format(self.sdc.case,self.ZorY)+suffix+'.png'), dpi=240) plt.close()
def test_dep(self): xf = arange(0, 425) deps = self.fm.get_dep(xf) plt.plot(xf,deps) plt.gca().set_yticks(self.fm.DEP) plt.gca().set_xticks(self.fm.Y_PC) plt.grid('on') plt.title('Ground x versus depth') plt.xlabel('Ground X (km)') plt.ylabel('depth (km)') plt.axis('equal') plt.gca().invert_yaxis() plt.savefig(join(self.outs_dir, '~Y_PC_vs_deps.png')) plt.close()
def plot(site): tp = np.loadtxt('../post_offsets/%s.post'%site) t = dc.asmjd([ii[0] for ii in tp]) + dc.adjust_mjd_for_plot_date e = [ii[1] for ii in tp] n = [ii[2] for ii in tp] u = [ii[3] for ii in tp] plt.plot_date(t,e,'x-', label = 'eastings') plt.plot(t,n,'x-', label = 'northings') plt.plot(t,u,'x-', label = 'upings') plt.gcf().autofmt_xdate() plt.legend(loc=0) plt.title(site) plt.savefig('%s.png'%site) #plt.show() plt.close()
def plot_baseline(data, plate_name, save_folder = r'Figures/'): """ """ colors = ((0.2, 0.2, 0.2), (0.5, 0.5, 0.5), (0.7, 0.7, 0.7), (0.3, 0.3, 0.3)) names = data.keys() names.sort() fig, axs = plt.subplots(figsize=(8,3)) for index, name in enumerate(names): for value in data[name]['original_data']: plot_color = colors[index % len(colors)] if abs(value - data[name]['mean'][0]) > data[name]['std'][0] * 2.0: axs.plot([value], [index], 'ko', markerfacecolor = [1,1,1]) else: axs.plot([value], [index], 'ko', color = plot_color) axs.plot([data[name]['mean'][0] for _ in xrange(2)], [index-0.25, index+0.25], 'k-') axs.plot([data[name]['mean'][0] - data[name]['std'][0] for _ in xrange(2)], [index-0.25, index+0.25], 'k--') axs.plot([data[name]['mean'][0] + data[name]['std'][0] for _ in xrange(2)], [index-0.25, index+0.25], 'k--') plt.yticks([i for i in xrange(len(names))], names, size = 10) plt.title(plate_name) plt.ylim(-0.5,len(names)-0.5) plt.xlabel('Fluorescent intensity') plt.tight_layout() save_filename = save_folder + 'baseline_average' pdf = PdfPages(save_filename.split('.')[0] + '.pdf') pdf.savefig(fig) pdf.close() plt.savefig(save_filename) # return None
def test_make_grids(self): north = 80 south = 12 east = 200 west = 80 dx = 200e3 dy = 200e3 grids = make_grids(north, south, west, east, dx, dy) lons = [ii[0] for ii in grids] lats = [ii[1] for ii in grids] bm = vj.plots.MyBasemap( region_box = (west+20, south-40, east+70, north), x_interval = 20, y_interval = 20) bm.plot(lons, lats, 'x', latlon=True) plt.savefig(join(self.outs_dir, 'map_gridding_point.png'))