Plot/Graph

MRAB python at mrabarnett.plus.com
Mon Apr 4 20:05:41 EDT 2016


On 2016-04-04 23:35, Muhammad Ali wrote:
> On Sunday, April 3, 2016 at 5:19:15 PM UTC-7, MRAB wrote:
>> 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" <muhammadaliaskari at gmail.com> 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 + '<http://matplotlib.org/examples/color/colormaps_reference.html>')
>> >          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 #<vmin will be set to vmin
>> >          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.
>
>
> I have posted the whole python script, please guide me which lines need to modify to get a single data file instead of plot using matplotlib.
>
> Thank you.
>
If you can run it, you should be able to set the args to make it save. 
It should be explained somewhere in the docs.

That script refers to things that must be coming from elsewhere, things 
that are not being imported explicitly by the script.




More information about the Python-list mailing list