12. GSASIIplot: plotting routines

This module performs all visualization using matplotlib and OpenGL graphics. The following plotting routines are defined:

plotting routine action
PlotPatterns() Powder pattern plotting
PublishRietveldPlot() Create publication-quality Rietveld plots from PlotPatterns() plot
PlotImage() Plots of 2D detector images
PlotPeakWidths() Plot instrument broadening terms as function of 2-theta/TOF
PlotCovariance() Show covariance terms in 2D
PlotStructure() Crystal structure plotting with balls, sticks, lines, ellipsoids, polyhedra and magnetic moments
PlotBeadModel() Plots representation of protein shape from small angle scattering
Plot1DSngl() 1D stick plots of structure factors
PlotSngl() Structure factor plotting
Plot3DSngl() 3D Structure factor plotting
PlotDeltSig() Normal probability plot (powder or single crystal)
PlotISFG() PDF analysis: displays I(Q), S(Q), F(Q) and G(r)
PlotCalib() CW or TOF peak calibration
PlotXY() Simple plot of xy data
PlotXYZ() Simple contour plot of xyz data
PlotXYZvect() Quiver Plot for 3D cartesian vectors
Plot3Dxyz() Surface Plot for 3D vectors
PlotAAProb() Protein “quality” plot
PlotStrain() Plot of strain data, used for diagnostic purposes
PlotSASDSizeDist() Small angle scattering size distribution plot
PlotPowderLines() Plot powder pattern as a stick plot (vertical lines)
PlotSizeStrainPO() Plot 3D mustrain/size/preferred orientation figure
PlotTexture() Pole figure, inverse pole figure plotting
ModulationPlot() Plots modulation information
PlotTorsion() Plots MC torsion angles
PlotRama() Ramachandran of energetically allowed regions for dihedral angles in protein
PlotSelectedSequence() Plot one or more sets of values selected from the sequential refinement table
PlotIntegration() Rectified plot of 2D image after image integration with 2-theta and azimuth as coordinates
PlotTRImage() test plot routine
PlotRigidBody() show rigid body structures as balls & sticks
PlotLayers() show layer structures as balls & sticks
PlotFPAconvolutors() plots the convolutors from Fundamental Parameters
:func:’PlotClusterYYZ’ plots the result of cluster analysis

These plotting routines place their graphics in the GSAS-II Plot Window, which contains a G2PlotNoteBook tabbed panel allowing multiple plots to be viewed. Methods G2PlotNoteBook.addMpl() (2-D matplotlib), G2PlotNoteBook.add3D() (3-D matplotlib), and G2PlotNoteBook.addOgl() (OpenGL) are used to create tabbed plot objects to hold plots of the following classes: G2PlotMpl (2-D matplotlib), G2Plot3D (3-D matplotlib), and G2PlotOgl (OpenGL). Note that two G2PlotNoteBook methods are potentially used to determine how plot updates after a refinement are handled:

class method description
G2PlotNoteBook.RegisterRedrawRoutine() This specifies a function to redraw the plot after the data tree has been reloaded. Be sure this updates data objects with new values from the tree, when needed.
G2PlotNoteBook.SetNoDelete() Use this to indicate that a plot does not need to be updated after a refinement and should not be closed.

These two methods define the following attributes (variables) in the plot tab classes:

variable default use
replotFunction None Defines a routine to be called to update the plot after a refinement (unless None). Use G2PlotNoteBook.RegisterRedrawRoutine() to define this (and replotArgs & replotKwArgs). Plotting functions that take significant time to complete should probably not use this.)
replotArgs [] Defines the positional arguments to be supplied to the replotFunction function or method.
replotKwArgs {} Defines the keyword arguments to be supplied to the replotFunction function or method.
plotRequiresRedraw True If set to True, after a refinement, the plot will be closed (in GSASIIdataGUI.GSASII.CleanupOldPlots()) if it was not updated after the refinement. Set this to False using G2PlotNoteBook.SetNoDelete() for plots that should not be deleted or do not change based on refinement results.
plotInvalid False Used to track if a plot has been updated. Set to False in G2PlotNoteBook.FindPlotTab() when a plot is drawn. After a refinement is completed, method GSASIIdataGUI.GSASII.ResetPlots() sets plotInvalid to False for all plots before any routines are called.

Note that the plot toolbar is customized with GSASIItoolbar

GSASIIplot.ComputeArc(angI, angO, wave, azm0=0, azm1=362)[source]

Computes arc/ring arrays in with inner and outer radii from angI,angO and beginning and ending azimuths azm0,azm1 (optional). Returns the inner and outer ring/arc arrays.

GSASIIplot.CopyRietveldPlot(G2frame, Pattern, Plot, Page, figure)[source]

Copy the contents of the Rietveld graph from the plot window to another mpl figure which can be on screen or can be a file for hard copy. Uses values from Pattern to also generate a delta/sigma plot below the main figure, since the weights are not available from the plot.

  • Pattern (list) – histogram object from data tree
  • Plot (mpl.axes) – The axes object from the Rietveld plot
  • Page (wx.Panel) – The tabbed panel for the Rietveld plot
  • figure (mpl.figure) – The figure object from the Rietveld plot
class GSASIIplot.G2Plot3D(parent, id=-1, dpi=None, **kwargs)[source]

Creates a 3D Matplotlib plot in the GSAS-II graphics window

class GSASIIplot.G2PlotMpl(parent, id=-1, dpi=None, publish=None, **kwargs)[source]

Creates a Matplotlib 2-D plot in the GSAS-II graphics window

class GSASIIplot.G2PlotNoteBook(parent, id=-1, G2frame=None)[source]

create a tabbed panel to hold a GSAS-II graphics window


delete a tabbed page

FindPlotTab(label, Type, newImage=True, publish=None)[source]

Open a plot tab for initial plotting, or raise the tab if it already exists Set a flag (Page.plotInvalid) that it has been redrawn Record the name of the this plot in self.lastRaisedPlotTab

  • label (str) – title of plot
  • Type (str) –

    determines the type of plot that will be opened.

    ’mpl’ for 2D graphs in matplotlib ‘ogl’ for openGL ‘3d’ for 3D plotting in matplotlib

  • newImage (bool) – forces creation of a new graph for matplotlib plots only (defaults as True)
  • publish (function) – reference to routine used to create a publication version of the current mpl plot (default is None, which prevents use of this).

new,plotNum,Page,Plot,limits where

  • new: will be True if the tab was just created
  • plotNum: is the tab number
  • Page: is the subclassed wx.Panel (G2PlotMpl, etc.) where the plot appears
  • Plot: the mpl.Axes object for the graphic (mpl) or the figure for openGL.
  • limits: for mpl plots, when a plot already exists, this will be a tuple with plot scaling. None otherwise.


Look up a tab label and return the index in the notebook (this appears to be independent to the order it is dragged to – at least in Windows) as well as the associated wx.Panel

An exception is raised if the label is not found


This is called to select an item from the tree using the self.allowZoomReset flag to prevent a reset to the zoom of the plot (where implemented)


Called when a keystroke event gets picked up by the notebook window rather the child. This is not expected, but somehow it does sometimes on the Mac and perhaps Linux.

Assume that the page associated with the currently displayed tab has a child, .canvas; give that child the focus and pass it the event.


respond to someone pressing a tab on the plot window. Called when a plot tab is clicked. on some platforms (Mac for sure) this is also called when a plot is created or selected with .SetSelection() or .SetFocus().

(removed) The self.skipPageChange is used variable is set to suppress repeated replotting.


Raises a plot tab without triggering a refresh via OnPageChanged

RegisterRedrawRoutine(name, routine=None, args=(), kwargs={})[source]

Save information to determine how to redraw a plot :param str name: label on tab of plot :param Object routine: a function to be called :param args: a list of positional parameters for the function :param kwargs: a dict with keyword parameters for the function

Rename(oldName, newName)[source]

rename a tab


Adds a Help button to the status bar on plots.

TODO: This has a problem with PlotPatterns where creation of the HelpButton causes the notebook tabs to be duplicated. A manual resize fixes that, but the SendSizeEvent has not worked.


Indicate that a plot does not need to be redrawn


Raises a plot tab without triggering a refresh via OnPageChanged


Add a tabbed page with a 3D plot

addMpl(name='', publish=None)[source]

Add a tabbed page with a matplotlib plot


Add a tabbed page with an openGL plot


clear all pages from plot window

class GSASIIplot.G2PlotOgl(parent, id=-1, dpi=None, **kwargs)[source]

Creates an OpenGL plot in the GSAS-II graphics window

class GSASIIplot.GSASIItoolbar(plotCanvas, publish=None, Arrows=True)[source]

Override the matplotlib toolbar so we can add more icons


reposition limits to scan or zoom by button press


Respond to press of help button on plot toolbar


Provide user with list of keystrokes defined for plot as well as an alternate way to access the same functionality


Return “ZOOM” if Zoom is active, , “PAN” if Pan is active, or None if neither


Turns off Zoom or Pan mode, if on. Ignored if neither is set

GSASIIplot.ModulationPlot(G2frame, data, atom, ax, off=0)[source]

Needs a description


Initiate the start of a Frame or Polygon map, etc. Called from a menu command (GSASIIimgGUI) or from OnImPlotKeyPress. Variable G2frame.MaskKey contains a single letter (‘f’ or ‘p’, etc.) that determines what type of mask is created.

Parameters:G2frame (wx.Frame) – The main GSAS-II tree “window”

Initiate the start of adding a new d-zero to a strain data set

  • G2frame (wx.Frame) – The main GSAS-II tree “window”
  • eventkey (str) – a single letter (‘a’) that triggers the addition of a d-zero.
GSASIIplot.Plot1DSngl(G2frame, newPlot=False, hklRef=None, Super=0, Title=False)[source]

1D Structure factor plotting package - displays reflections as sticks proportional to F, F**2, etc. as requested

GSASIIplot.Plot3DSngl(G2frame, newPlot=False, Data=None, hklRef=None, Title=False)[source]

3D Structure factor plotting package - displays reflections as spots proportional to F, F**2, etc. as requested as 3D array via pyOpenGl

GSASIIplot.PlotAAProb(G2frame, resNames, Probs1, Probs2, Title='', thresh=None, pickHandler=None)[source]

Needs a description

GSASIIplot.PlotBarGraph(G2frame, Xarray, Xname='', Yname='Number', Title='', PlotName=None, ifBinned=False, maxBins=None)[source]

does a vertical bar graph

GSASIIplot.PlotBeadModel(G2frame, Atoms, defaults, PDBtext)[source]

Bead modelplotting package. For bead models from SHAPES

GSASIIplot.PlotCalib(G2frame, Inst, XY, Sigs, newPlot=False)[source]

plot of CW or TOF peak calibration

GSASIIplot.PlotClusterXYZ(G2frame, YM, XYZ, CLuDict, Title='', PlotName='cluster')[source]

To plot cluster analysis results :param wx.Frame G2frame: The main GSAS-II tree “window” :param array YM: data matrix; plotted as contour :param array XYZ: array of 3D PCA coordinates; plotted as 3D scatter plot ;param dict CLuDict: Cluster info; may have dendrogram & Kmeans results :param str Title: plot title :param str PlotName: plot tab name

GSASIIplot.PlotCovariance(G2frame, Data)[source]

Plots the covariance matrix. Also shows values for parameters and their standard uncertainties (esd’s) or the correlation between variables.

GSASIIplot.PlotDeltSig(G2frame, kind, PatternName=None)[source]

Produces normal probability plot for a powder or single crystal histogram

GSASIIplot.PlotExposedImage(G2frame, newPlot=False, event=None)[source]

General access module for 2D image plotting

GSASIIplot.PlotFPAconvolutors(G2frame, NISTpk, conv2T=None, convI=None, convList=None)[source]

Plot the convolutions used for the current peak computed with GSASIIfpaGUI.doFPAcalc()

GSASIIplot.PlotISFG(G2frame, data, newPlot=False, plotType='', peaks=None)[source]

Plotting package for PDF analysis; displays I(Q), S(Q), F(Q) and G(r) as single or multiple plots with waterfall and contour plots as options

GSASIIplot.PlotImage(G2frame, newPlot=False, event=None, newImage=True)[source]

Plot of 2D detector images as contoured plot. Also plot calibration ellipses, masks, etc. Plots whatever is in G2frame.ImageZ

  • G2frame (wx.Frame) – main GSAS-II frame
  • newPlot (bool) – if newPlot is True, the plot is reset (zoomed out, etc.)
  • event – matplotlib mouse event (or None)
  • newImage (bool) – If True, the Figure is cleared and redrawn
GSASIIplot.PlotIntegration(G2frame, newPlot=False, event=None)[source]

Plot of 2D image after image integration with 2-theta and azimuth as coordinates

GSASIIplot.PlotLayers(G2frame, Layers, laySeq, defaults)[source]

Layer plotting package. Can show layer structures as balls & sticks

GSASIIplot.PlotNamedFloatHBarGraph(G2frame, Xvals, Ynames, Xlabel='Value', Ylabel='', Title='', PlotName=None)[source]

does a horizintal bar graph

GSASIIplot.PlotPatterns(G2frame, newPlot=False, plotType='PWDR', data=None, extraKeys=[], refineMode=False)[source]

Powder pattern plotting package - displays single or multiple powder patterns as intensity vs 2-theta, q or TOF. Can display multiple patterns as “waterfall plots” or contour plots. Log I plotting available.

Note that plotting information will be found in:

G2frame.PatternId (contains the tree item for the current histogram)

G2frame.PickId (contains the actual selected tree item (can be child of histogram)

G2frame.HKL (used for tool tip display of hkl for selected phase reflection list)

GSASIIplot.PlotPeakWidths(G2frame, PatternName=None)[source]

Plotting of instrument broadening terms as function of 2-theta Seen when “Instrument Parameters” chosen from powder pattern data tree. Parameter PatternName allows the PWDR to be referenced as a string rather than a wx tree item, defined in G2frame.PatternId.


plotting of powder lines (i.e. no powder pattern) as sticks

GSASIIplot.PlotRama(G2frame, phaseName, Rama, RamaName, Names=[], PhiPsi=[], Coeff=[])[source]

needs a doc string

GSASIIplot.PlotRawImage(G2frame, image, label, newPlot=False)[source]

Plot an image without axes etc.

GSASIIplot.PlotRigidBody(G2frame, rbType, AtInfo, rbData, defaults)[source]

RB plotting package. Can show rigid body structures as balls & sticks


Needs a description


Needs a description

GSASIIplot.PlotSelectedSequence(G2frame, ColumnList, TableGet, SelectX, fitnum=None, fitvals=None)[source]

Plot a result from a sequential refinement

  • G2frame (wx.Frame) – The main GSAS-II tree “window”
  • ColumnList (list) – list of int values corresponding to columns selected as y values
  • TableGet (function) – a function that takes a column number as argument and returns the column label, the values and there ESDs (or None)
  • SelectX (function) – a function that returns a selected column number (or None) as the X-axis selection
GSASIIplot.PlotSizeStrainPO(G2frame, data, hist='', Start=False)[source]

Plot 3D mustrain/size/preferred orientation figure. In this instance data is for a phase

GSASIIplot.PlotSngl(G2frame, newPlot=False, Data=None, hklRef=None, Title='')[source]

Structure factor plotting package - displays zone of reflections as rings proportional to F, F**2, etc. as requested via matpltlib; plots are not geometrically correct

GSASIIplot.PlotStrain(G2frame, data, newPlot=False)[source]

plot of strain data, used for diagnostic purposes

GSASIIplot.PlotStructure(G2frame, data, firstCall=False, pageCallback=None)[source]

Crystal structure plotting package. Can show structures as balls, sticks, lines, thermal motion ellipsoids and polyhedra. Magnetic moments shown as black/red arrows according to spin state

  • G2frame (wx.Frame) – main GSAS-II window
  • data (dict) – dict with plotting information (see Phase Tree object)
  • firstCall (bool) – If True, this is the initial call and causes the plot to be shown twice (needed for Mac and possibly linux)
  • pageCallback (function) – a callback function to update items on the parent page. Currently implemented for RB Models tab only
GSASIIplot.PlotTRImage(G2frame, tax, tay, taz, newPlot=False)[source]

a test plot routine - not normally used

GSASIIplot.PlotTexture(G2frame, data, Start=False)[source]

Pole figure, inverse pole figure plotting. dict generalData contains all phase info needed which is in data

GSASIIplot.PlotTorsion(G2frame, phaseName, Torsion, TorName, Names=[], Angles=[], Coeff=[])[source]

needs a doc string

GSASIIplot.PlotXY(G2frame, XY, XY2=[], labelX='X', labelY='Y', newPlot=False, Title='', lines=False, names=[], names2=[], vertLines=[])[source]

simple plot of xy data

  • G2frame (wx.Frame) – The main GSAS-II tree “window”
  • XY (list) – a list of X,Y array pairs; len(X) = len(Y)
  • XY2 (list) – a secondary list of X,Y pairs
  • labelX (str) – label for X-axis
  • labelY (str) – label for Y-axis
  • newPlot (bool) – =True if new plot is to be made
  • Title (str) – title for plot
  • lines (bool) – = True if lines desired for XY plot; XY2 always plotted as lines
  • names (list) – legend names for each XY plot as list a of str values
  • names2 (list) – legend names for each XY2 plot as list a of str values
  • vertLines (list) – lists of vertical line x-positions; can be one for each XY


GSASIIplot.PlotXYZ(G2frame, XY, Z, labelX='X', labelY='Y', newPlot=False, Title='', zrange=None, color=None, buttonHandler=None)[source]

simple contour plot of xyz data

  • G2frame (wx.Frame) – The main GSAS-II tree “window”
  • XY (list) – a list of X,Y arrays
  • Z (list) – a list of Z values for each X,Y pair
  • labelX (str) – label for X-axis
  • labelY (str) – label for Y-axis
  • newPlot (bool) – =True if new plot is to be made
  • Title (str) – title for plot
  • zrange (list) – [zmin,zmax]; default=None to use limits in Z
  • color (str) – one of mpl.cm.dated.keys(); default=None to use G2frame.ContourColor


GSASIIplot.PlotXYZvect(G2frame, X, Y, Z, R, labelX='X', labelY='Y', labelZ='Z', Title='', PlotName=None)[source]

To plot a quiver of quaternion vectors colored by the rotation :param wx.Frame G2frame: The main GSAS-II tree “window” :param list X,Y,Z: list of X,Y,Z arrays :param list R: a list of rotations (0-90) for each X,Y,Z in degrees :param str labelX,labelY,labelZ: labels for X,Y,Z-axes :param str Title: plot title :param str PlotName: plot tab name

GSASIIplot.PublishRietveldPlot(G2frame, Pattern, Plot, Page)[source]

Show a customizable “Rietveld” plot and export as a publication-quality file. Will only work when a single pattern is displayed.

  • G2Frame (wx.Frame) – the main GSAS-II window
  • Pattern (list) – list of np.array items with obs, calc (etc.) diffraction pattern
  • Plot (mpl.axes) – axes of the graph in plot window
  • Page (wx.Panel) – tabbed panel containing the plot
GSASIIplot.ReplotPattern(G2frame, newPlot, plotType, PatternName=None, PickName=None)[source]

This does the same as PlotPatterns except that it expects the information to be plotted (pattern name, item picked in tree + eventually the reflection list) to be passed as names rather than references to wx tree items, defined as class entries


Turns on and off MultiSpot selection mode; displays a subtitle on plot the is cleared by the next PlotImage call

GSASIIplot.UpdatePolygon(pick, event, polygon)[source]

Update a polygon (or frame) in response to the location of the mouse. Delete the selected point if moved on top of another. With right button add a point after the current button.

GSASIIplot.Write2csv(fil, dataItems, header=False)[source]

Write a line to a CSV file

  • fil (object) – file object
  • dataItems (list) – items to write as row in file
  • header (bool) – True if all items should be written with quotes (default is False)
GSASIIplot.changePlotSettings(G2frame, Plot)[source]

Code in development to allow changes to plot settings prior to export of plot with “floppy disk” button


When a line in the legend is selected, find the matching line in the plot and then highlight it by adding/enlarging markers. Set up a timer to make a reset after delay selected in SetupLegendPick