Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: MRAB Newsgroups: comp.lang.python Subject: Re: Plot/Graph Date: Mon, 4 Apr 2016 01:18:49 +0100 Lines: 294 Message-ID: References: <768f1e2e-baab-4ce3-ae4e-aab2d8ac5bf8@googlegroups.com> <20f8e8fb-0bb8-4daa-8d68-d0cc3699a6fc@googlegroups.com> <10a26eef-d271-4202-902e-751eb5495a80@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de VJHB60NIOpoeyLXHh+ZR1wztyiZqDXdjVYapCVRddGjg== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'args': 0.04; 'elif': 0.04; 'modified': 0.05; 'skip:p 60': 0.05; '__name__': 0.07; 'below)': 0.07; 'extracted': 0.07; 'none)': 0.07; 'none):': 0.07; 'skip:\\ 10': 0.07; '"%s"': 0.09; "'.'": 0.09; 'alternatives': 0.09; 'benjamin': 0.09; 'csv': 0.09; 'docs.': 0.09; 'newly': 0.09; 'posted.': 0.09; 'skip:[ 30': 0.09; 'python': 0.10; 'def': 0.13; "skip:' 30": 0.15; 'skip:f 30': 0.15; 'skip:p 40': 0.15; "'__main__':": 0.16; "'to',": 0.16; '(%s):': 0.16; '-1.0': 0.16; '2016': 0.16; 'expects': 0.16; 'from:addr:mrabarnett.plus.com': 0.16; 'from:addr:python': 0.16; 'from:name:mrab': 0.16; 'message-id:@mrabarnett.plus.com': 0.16; 'origin.': 0.16; 'received:192.168.1.4': 0.16; 'received:84.93': 0.16; 'received:84.93.230': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'skip:{ 40': 0.16; 'sys.exit(0)': 0.16; 'wrote:': 0.16; 'drawing': 0.18; 'skip:l 30': 0.18; 'prevent': 0.20; 'skip:" 40': 0.20; 'disable': 0.22; 'pos': 0.22; 'skip:% 10': 0.22; 'skip:l 40': 0.23; 'slightly': 0.23; 'header:In-Reply- To:1': 0.24; 'module': 0.25; 'script': 0.25; 'header:User- Agent:1': 0.26; 'skip:" 20': 0.26; 'figure': 0.27; 'points': 0.27; 'scale': 0.27; 'question': 0.27; 'defining': 0.27; 'skip:e 30': 0.27; 'skip:i 40': 0.27; "skip:' 10": 0.28; 'values': 0.28; 'skip:( 20': 0.28; 'origin': 0.29; 'skip:k 30': 0.29; 'vertical': 0.29; 'print': 0.30; 'subject:/': 0.30; 'creating': 0.30; 'code': 0.30; 'skip:g 30': 0.30; 'skip:s 30': 0.31; 'option': 0.31; 'another': 0.32; 'skip:- 30': 0.32; 'computing': 0.32; 'received:84': 0.32; 'maybe': 0.33; 'file': 0.34; 'previous': 0.34; 'skip:d 20': 0.34; 'running': 0.34; 'add': 0.34; 'that,': 0.34; 'list': 0.34; 'skip:( 30': 0.35; 'skip:c 30': 0.35; 'could': 0.35; 'done': 0.35; 'fail': 0.35; 'false': 0.35; 'label': 0.35; 'saved': 0.35; 'item': 0.35; 'skip:p 30': 0.35; 'according': 0.36; 'skip:i 20': 0.36; 'instead': 0.36; 'url:org': 0.36; 'lines': 0.36; 'tool': 0.36; 'depends': 0.36; 'skip:m 40': 0.36; 'smaller': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'display': 0.37; 'skip:s 50': 0.37; 'building': 0.38; 'skip:p 20': 0.38; 'files': 0.38; 'skip:o 20': 0.38; 'end': 0.39; 'data': 0.39; 'format': 0.39; 'does': 0.39; 'received:192': 0.39; 'rather': 0.39; 'skip:x 10': 0.40; 'to:addr:python.org': 0.40; 'where': 0.40; 'some': 0.40; 'software': 0.40; 'high': 0.60; 'show': 0.62; 'skip:n 10': 0.62; 'more': 0.63; 'different': 0.63; 'positions': 0.64; 'results': 0.66; 'color': 0.67; 'choose': 0.68; 'saving': 0.70; '100': 0.79; '(300': 0.84; '3))': 0.84; 'contour': 0.84; 'oscar': 0.84; 'presumably': 0.84; 'utc-7,': 0.84; 'min': 0.91; 'ali': 0.95 X-CM-Score: 0.00 X-CNFS-Analysis: v=2.1 cv=bsGxfxui c=1 sm=1 tr=0 a=0nF1XD0wxitMEM03M9B4ZQ==:117 a=0nF1XD0wxitMEM03M9B4ZQ==:17 a=L9H7d07YOLsA:10 a=9cW_t1CCXrUA:10 a=s5jvgZ67dGcA:10 a=IkcTkHD0fZMA:10 a=pGLkceISAAAA:8 a=quRTTRacAAAA:8 a=YeGnY8NiDA3ebqTMerwA:9 a=ZpgL85ijKJuol_Qe:21 a=szhU7MIgciREmGJ3:21 a=QEXdDO2ut3YA:10 a=dktroZwzVEUA:10 X-AUTH: mrabarnett@:2500 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.7.1 In-Reply-To: <10a26eef-d271-4202-902e-751eb5495a80@googlegroups.com> X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:106419 On 2016-04-04 01:04, Muhammad Ali wrote: > On Sunday, April 3, 2016 at 2:35:58 PM UTC-7, Oscar Benjamin wrote: >> On 3 Apr 2016 22:21, "Muhammad Ali" wrote: >> > >> > How do I convert/change/modify python script so that my data could be >> extracted according to python script and at the end it generates another >> single extracted data file instead of displaying/showing some graph? So >> that, I can manually plot the newly generated file (after data extraction) >> by some other software like origin. >> >> It depends what you're computing and what format origin expects the data to >> be in. Presumably it can use CSV files so take a look at the CSV module >> which can write these. >> >> (You'll get better answers to a question like this if you show us some code >> and ask a specific question about how to change it.) >> >> -- >> Oscar > > How could the python script be modified to generate data file rather than display a plot by using matplotlib? > > > def make_plot(plot): > indent = plot.plot_options.indent > args = plot.plot_options.args > # Creating the plot > print ('Generating the plot...') > fig = plt.figure(figsize=(plot.fig_width_inches,plot.fig_height_inches)) > ax = fig.add_subplot(111) > # Defining the color schemes. > print (indent + '>>> Using the "' + plot.cmap_name + '" colormap.') > if(plot.plot_options.using_default_cmap and not args.running_from_GUI): > print (2 * indent + 'Tip: You can try different colormaps by either:') > print (2 * indent + ' * Running the plot tool with the option -icmap n, ' \ > 'with n in the range from 0 to', len(plot.plot_options.cmaps) - 1) > print (2 * indent + ' * Running the plot tool with the option "-cmap cmap_name".') > print (2 * indent + '> Take a look at') > print (4 * indent + '') > print (2 * indent + ' for a list of colormaps, or run') > print (4 * indent + '"./plot_unfolded_EBS_BandUP.py --help".') > > # Building the countour plot from the read data > # Defining the (ki,Ej) grid. > if(args.interpolation is not None): > ki = np.linspace(plot.kmin, plot.kmax, 2 * len(set(plot.KptsCoords)) + 1, endpoint=True) > Ei = np.arange(plot.emin, plot.emax + plot.dE_for_hist2d, plot.dE_for_hist2d) > # Interpolating > grid_freq = griddata((plot.KptsCoords, plot.energies), plot.delta_Ns, (ki[None,:], Ei[:,None]), > method=args.interpolation, fill_value=0.0) > else: > ki = np.unique(np.clip(plot.KptsCoords, plot.kmin, plot.kmax)) > Ei = np.unique(np.clip(plot.energies, plot.emin, plot.emax)) > grid_freq = griddata((plot.KptsCoords, plot.energies), plot.delta_Ns, (ki[None,:], Ei[:,None]), > method='nearest', fill_value=0.0) > > if(not args.skip_grid_freq_clip): > grid_freq = grid_freq.clip(0.0) # Values smaller than zero are just noise. > # Normalizing and building the countour plot > manually_normalize_colorbar_min_and_maxval = False > if((args.maxval_for_colorbar is not None) or (args.minval_for_colorbar is not None)): > manually_normalize_colorbar_min_and_maxval = True > args.disable_auto_round_vmin_and_vmax = True > maxval_for_colorbar = args.maxval_for_colorbar > minval_for_colorbar = args.minval_for_colorbar > else: > if not args.disable_auto_round_vmin_and_vmax: > minval_for_colorbar = float(round(np.min(grid_freq))) > maxval_for_colorbar = float(round(np.max(grid_freq))) > args.round_cb = 0 > if(manually_normalize_colorbar_min_and_maxval or not args.disable_auto_round_vmin_and_vmax): > modified_vmin_or_vmax = False > if not args.disable_auto_round_vmin_and_vmax and not args.running_from_GUI: > print (plot.indent + '* Automatically renormalizing color scale '\ > '(you can disable this with the option --disable_auto_round_vmin_and_vmax):') > if manually_normalize_colorbar_min_and_maxval: > print (plot.indent + '* Manually renormalizing color scale') > if(minval_for_colorbar is not None): > previous_vmin = np.min(grid_freq) > if(abs(previous_vmin - minval_for_colorbar) >= 0.1): > modified_vmin_or_vmax = True > print (2 * indent + 'Previous vmin = %.1f, new vmin = %.1f' % (previous_vmin, > minval_for_colorbar)) > else: > minval_for_colorbar = np.min(grid_freq) > if(maxval_for_colorbar is not None): > previous_vmax = np.max(grid_freq) > if(abs(previous_vmax - maxval_for_colorbar) >= 0.1): > modified_vmin_or_vmax = True > print (2 * indent + 'Previous vmax = %.1f, new vmax = %.1f' % (previous_vmax, > maxval_for_colorbar)) > else: > maxval_for_colorbar = np.max(grid_freq) > if(modified_vmin_or_vmax): > print (2 * indent + 'The previous vmin and vmax might be slightly different from ' > 'the min and max delta_Ns ' > 'due to the interpolation scheme used for the plot.') > # values > vmax will be set to vmax, and # grid_freq = grid_freq.clip(minval_for_colorbar, maxval_for_colorbar) > v = np.linspace(minval_for_colorbar, maxval_for_colorbar, args.n_levels, endpoint=True) > else: > v = np.linspace(np.min(grid_freq), np.max(grid_freq), args.n_levels, endpoint=True) > print (indent + '* Drawing contour plot...') > print (2 * indent + '> Using %i color levels. Use the option "--n_levels" to choose a different number.' %args.n_levels) > image = ax.contourf(ki, Ei, grid_freq, levels=v, cmap=plot.cmap) > > plot_spin_proj_requested = args.plot_spin_perp or args.plot_spin_para or args.plot_sigma_x or args.plot_sigma_y or args.plot_sigma_z > if(plot_spin_proj_requested and plot.spin_projections is not None): > print (indent + '* Drawing spin projection info') > cmap_for_spin_plot = [plt.cm.bwr, plt.cm.RdBu, plt.cm.seismic_r][0] > > if(args.clip_spin is None): > vmin_spin = np.min(plot.spin_projections) > vmax_spin = np.max(plot.spin_projections) > else: > vmax_spin = abs(args.clip_spin) > vmin_spin = -1.0 * abs(args.clip_spin) > print (2 * indent + '* New maxval for spin: %.2f' % vmax_spin) > print (2 * indent + '* New minval for spin: %.2f' % vmin_spin) > > spin_projections = np.clip(plot.spin_projections, vmin_spin, vmax_spin) > grid_freq_spin = griddata((plot.KptsCoords, plot.energies), spin_projections, (ki[None,:], Ei[:,None]), > method='nearest', fill_value=0.0) > > k_for_scatter = [] > E_for_scatter = [] > spin_projections_for_scatter = [] > for iener in range(len(Ei)): > for ikpt in range(len(ki)): > if(abs(grid_freq_spin[iener, ikpt]) > 1E-3): > k_for_scatter.append(ki[ikpt]) > E_for_scatter.append(Ei[iener]) > spin_projections_for_scatter.append(grid_freq_spin[iener, ikpt]) > > if(spin_projections_for_scatter): > if(args.spin_marker=='o'): > image2 = ax.scatter(k_for_scatter, E_for_scatter, marker='o', > s=[10.0 * abs(item) for item in spin_projections_for_scatter], > c=spin_projections_for_scatter, cmap=cmap_for_spin_plot) > else: > image2 = ax.scatter(k_for_scatter, E_for_scatter, marker='_', > s=[500.0 * (ki[1] - ki[0]) for item in spin_projections_for_scatter], > linewidth=[100.0 * plot.dE_for_hist2d * (item ** 2) for item in spin_projections_for_scatter], > c=spin_projections_for_scatter, cmap=cmap_for_spin_plot) > else: > print (2 * indent + '* The abs values of the spin projections were all < 1E-3.') > > #Preparing the plot > ax.set_xlim(plot.kmin, plot.kmax) > ax.set_ylim(plot.emin, plot.emax) > ax.set_title(plot.title, fontsize=plot.title_size) > ax.set_ylabel(plot.y_axis_label, fontsize=plot.yaxis_labels_size) > plt.yticks(fontsize=plot.tick_marks_size) > > # Fermi energy line > show_E_f = not args.no_ef > if(show_E_f and plot.E_f >= plot.emin and plot.E_f <= plot.emax): > E_f_line = plt.axhline(y=plot.E_f, c=plot.color_E_f_line(image), linestyle=plot.line_style_E_f, lw=plot.line_width_E_f) > # High symmetry points lines > if(plot.pos_high_symm_points): > x_tiks_positions = [kx for kx in plot.pos_high_symm_points if kx - plot.kmax <= 1E-2 and kx >= plot.kmin] > if(args.no_symm_labels): > x_tiks_labels = [] > else: > x_tiks_labels = [plot.labels_high_symm_lines[i] for i in range(len(plot.labels_high_symm_lines)) if > plot.pos_high_symm_points[i] in x_tiks_positions] > x_tiks_labels = [xlabel for xlabel in x_tiks_labels if xlabel] > if x_tiks_labels: > print (indent + '* K-point labels read from the "' + args.kpoints_file + '" file:') > for ilabel in range(len(x_tiks_labels)): > print(2 * indent + "k = {:9.5f}".format(x_tiks_positions[ilabel]) + ', label =',\ > x_tiks_labels[ilabel]) > plt.xticks(x_tiks_positions, x_tiks_labels, fontsize=plot.tick_marks_size) > else: > plot.x_axis_label = '$k \hspace{0.25} (\AA^{-1})$' > plt.locator_params(axis = 'x', nbins = 5) > ax.set_xlabel(plot.x_axis_label, fontsize=plot.xaxis_labels_size) > plt.xticks(fontsize=plot.tick_marks_size) > ax.tick_params(axis='x', pad=10) > > # Drawing vertical lines at the positions of the high-symmetry points > if(not args.no_symm_lines): > for line_position in [pos for pos in plot.pos_high_symm_points if float(round(pos, 3)) > float(round(plot.kmin, 3)) and > float(round(pos, 3)) < float(round(plot.kmax, 3))]: > hs_lines = plt.axvline(x=line_position, c=plot.color_high_symm_lines(image), linestyle=plot.line_style_high_symm_points, > lw=plot.line_width_high_symm_points) > > # Color bar > show_colorbar = not args.no_cb > if show_colorbar: > if plot.cb_orientation=='vertical': > cb_pad=0.005 > else: > cb_pad=0.06 > if(not x_tiks_labels): > cb_pad += 0.08 # To prevent the cb from overlapping with the numbers. > > cb_yticks = np.arange(int(image.norm.vmin), int(image.norm.vmax) + 1, 1) > > cb_ytick_labels = [round(item,abs(args.round_cb)) for item in cb_yticks] > cb = plt.colorbar(image, ax=ax, ticks=cb_yticks, orientation=plot.cb_orientation, pad=cb_pad) > cb.set_ticklabels(cb_ytick_labels) > cb.ax.tick_params(labelsize=plot.colorbar_tick_marks_size) > > color_bar_label = None > if args.cb_label: > color_bar_label = ('$Color scale: \hspace{0.5} \delta N(\\vec{k}; ' + > '\hspace{0.25} \epsilon)$ ') > if args.cb_label_full: > color_bar_label = ('$Colors cale: \hspace{0.5} \delta N(\\vec{k}; ' + > '\hspace{0.25} \epsilon);$ '+ > '$\delta\epsilon=' + round(1000.0*plot.dE_for_hist2d,0) + > '\\hspace{0.25} meV.$') > > if plot.cb_orientation=='vertical': > cb_label_rotation = 90 > else: > cb_label_rotation = 0 > if color_bar_label: > cb.ax.text(plot.offset_x_text_colorbar, plot.offset_y_text_colorbar, > color_bar_label, rotation=cb_label_rotation, ha='center', > va='center', fontsize=plot.colorbar_label_size) > > # Saving/showing the results > plt.tick_params(which='both', bottom='off', top='off', left='off', right='off', > labelbottom='on') > > > default_out_basename = "_".join([splitext(basename(args.input_file))[0], 'E_from', str(plot.emin), 'to', > str(plot.emax), 'eV_dE', > str(plot.dE_for_hist2d), 'eV']) > if(args.save): > if(args.output_file is None): > args.output_file = abspath(default_out_basename + '.' + args.file_format) > > print ('Savig figure to file "%s" ...' % args.output_file) > if(args.fig_resolution[0].upper() == 'H'): > print (indent + '* High-resolution figure (600 dpi).') > fig_resolution_in_dpi = 600 > elif (args.fig_resolution[0].upper() == 'M'): > print (indent + '* Medium-resolution figure (300 dpi).') > fig_resolution_in_dpi = 300 > elif (args.fig_resolution[0].upper() == 'L'): > print (indent + '* Low-resolution figure (100 dpi).') > fig_resolution_in_dpi = 100 > else: > print (indent + 'Assuming medium-resolution (300 dpi) for the figure.') > fig_resolution_in_dpi = 300 > plt.savefig(args.output_file, dpi=fig_resolution_in_dpi, bbox_inches='tight') > print (indent + '* Done saving figure (%s).' % args.output_file) > > if args.saveshow: > print ('Opening saved figure (%s)...' % default_out_basename) > # 'xdg-open' might fail to find the defualt program in some systems > # For such cases, one can try to use other alternatives (just add more to the list below) > image_viewer_list = ['xdg-open', 'eog'] > for image_viewer in image_viewer_list: > open_saved_fig = Popen([image_viewer, args.output_file], stdout=PIPE, stderr=PIPE) > std_out, std_err = open_saved_fig.communicate() > success_opening_file = std_err.strip() == '' > if(success_opening_file): > break > if(not success_opening_file): > print (indent + '* Failed (%s): no image viewer detected.' % default_out_basename) > > if args.show: > print ('Showing figure (%s)...' % default_out_basename) > plt.show() > print (indent + '* Done showing figure (%s).' % default_out_basename) > > > if __name__ == '__main__': > print_opening_message() > plot_options = BandUpPlotOptions() > plot = BandUpPlot(plot_options) > make_plot(plot) > sys.exit(0) > Look at the line "if(args.save):". That decides whether to save. Where does args come from? It comes from "args = plot.plot_options.args". "plot" is passed into "make_plot". Where does that object come from? It comes from "plot = BandUpPlot(plot_options)". Where does "plot_options" come from? It comes from "plot_options = BandUpPlotOptions()". What's "BandUpPlotOptions()"? I have no idea. It's not part of what you've posted. Now, over to you to do the rest. Maybe it's mentioned in matplotlib's docs.