13. GSASIIplot: plotting routines

13.1. Summary/Contents

Routines for visualization, using matplotlib and OpenGL graphics. Note that the plot toolbar is customized with GSASIItoolbar

13.2. List of Graphics routines

The following plotting routines are defined:

plotting routine



Powder pattern plotting


Create publication-quality Rietveld plots from PlotPatterns() plot


Plots of 2D detector images


Plot instrument broadening terms as function of 2-theta/TOF


Show covariance terms in 2D


Crystal structure plotting with balls, sticks, lines, ellipsoids, polyhedra and magnetic moments


Plots representation of protein shape from small angle scattering


1D stick plots of structure factors


Structure factor plotting


3D Structure factor plotting


Normal probability plot (powder or single crystal)


PDF analysis: displays I(Q), S(Q), F(Q) and G(r)


CW or TOF peak calibration


Simple plot of xy data


Simple contour plot of xyz data


Quiver Plot for 3D cartesian vectors


Surface Plot for 3D vectors


Protein “quality” plot


Plot of strain data, used for diagnostic purposes


Small angle scattering size distribution plot


Plot powder pattern as a stick plot (vertical lines)


Plot 3D mustrain/size/preferred orientation figure


Pole figure, inverse pole figure plotting


Plots modulation information


Plots MC torsion angles


Ramachandran of energetically allowed regions for dihedral angles in protein


Plot one or more sets of values selected from the sequential refinement table


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


test plot routine


show rigid body structures as balls & sticks


show layer structures as balls & sticks


plots the convolutors from Fundamental Parameters


plots the result of cluster analysis

13.3. Window management routines

The above 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



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.


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:






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.)



Defines the positional arguments to be supplied to the replotFunction function or method.



Defines the keyword arguments to be supplied to the replotFunction function or method.



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.



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.

13.4. GSASIIplot Classes and routines

Classes and routines defined in GSASIIplot follow.

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 (matplotlib.figure.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

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

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

__init__(parent, id=-1, dpi=None, publish=None, **kwargs)[source]
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

__init__(parent, id=-1, G2frame=None)[source]
_addPage(name, page)[source]

Add the newly created page to the notebook and associated lists. :param name: the label placed on the tab, which should be unique :param page: the wx.Frame for the matplotlib, openGL, etc. window


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

__init__(parent, id=-1, dpi=None, **kwargs)[source]
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

__init__(plotCanvas, publish=None, Arrows=True)[source]

Adds additional icons to toolbar


Overrides the post-buttonbar update action to invoke a redraw; needed for plot magnification


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


this removes spurious text messages from the tool bar

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.


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.Plot3dXYZ(G2frame, nX, nY, Zdat, labelX='X', labelY='Y', labelZ='Z', newPlot=False, Title='', Centro=False)[source]

Creates a surface Plot for 3D vectors

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, Cube=False)[source]

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

GSASIIplot.PlotDeform(G2frame, general, atName, atType, deform, UVmat, neigh)[source]

Plot deformation atoms & neighbors

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 Q 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='')[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._Old_Paired_data = {'blue': [(0.0, 0.8901960849761963, 0.8901960849761963), (0.09090909090909091, 0.7058823704719543, 0.7058823704719543), (0.18181818181818182, 0.5411764979362488, 0.5411764979362488), (0.2727272727272727, 0.1725490242242813, 0.1725490242242813), (0.36363636363636365, 0.6000000238418579, 0.6000000238418579), (0.45454545454545453, 0.10980392247438431, 0.10980392247438431), (0.5454545454545454, 0.43529412150382996, 0.43529412150382996), (0.6363636363636364, 0.0, 0.0), (0.7272727272727273, 0.8392156958580017, 0.8392156958580017), (0.8181818181818182, 0.6039215922355652, 0.6039215922355652), (0.9090909090909091, 0.6000000238418579, 0.6000000238418579), (1.0, 0.1568627506494522, 0.1568627506494522)], 'green': [(0.0, 0.8078431487083435, 0.8078431487083435), (0.09090909090909091, 0.47058823704719543, 0.47058823704719543), (0.18181818181818182, 0.8745098114013672, 0.8745098114013672), (0.2727272727272727, 0.6274510025978088, 0.6274510025978088), (0.36363636363636365, 0.6039215922355652, 0.6039215922355652), (0.45454545454545453, 0.10196078568696976, 0.10196078568696976), (0.5454545454545454, 0.7490196228027344, 0.7490196228027344), (0.6363636363636364, 0.49803921580314636, 0.49803921580314636), (0.7272727272727273, 0.6980392336845398, 0.6980392336845398), (0.8181818181818182, 0.239215686917305, 0.239215686917305), (0.9090909090909091, 1.0, 1.0), (1.0, 0.3490196168422699, 0.3490196168422699)], 'red': [(0.0, 0.6509804129600525, 0.6509804129600525), (0.09090909090909091, 0.12156862765550613, 0.12156862765550613), (0.18181818181818182, 0.6980392336845398, 0.6980392336845398), (0.2727272727272727, 0.20000000298023224, 0.20000000298023224), (0.36363636363636365, 0.9843137264251709, 0.9843137264251709), (0.45454545454545453, 0.8901960849761963, 0.8901960849761963), (0.5454545454545454, 0.9921568632125854, 0.9921568632125854), (0.6363636363636364, 1.0, 1.0), (0.7272727272727273, 0.7921568751335144, 0.7921568751335144), (0.8181818181818182, 0.4156862795352936, 0.4156862795352936), (0.9090909090909091, 1.0, 1.0), (1.0, 0.6941176652908325, 0.6941176652908325)]}

This can be done on request for other colors - any new names must be explicitly added to color list obtained from mpl.cm.datad.keys() (currently 10 places in GSAS-II code)

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

Creates a basic tabbed plot window for GSAS-II graphics

__init__(parent, id=-1, dpi=None, **kwargs)[source]
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

GSASIIplot.uneqImgShow(figure, ax, Xlist, Ylist, cmap, vmin, vmax, Ylbls=[])[source]

Plots a contour plot where point spacing varies within a dataset and where the X values may differ between histograms. Note that the length of Xlist and Ylist must be the same and will be the number of histograms to be plotted

  • figure (matplotlib.figure) – The figure where the plot will be placed.

  • ax (matplotlib.axes) – The axes where the plot will be made.

  • Xlist (list) – A list of X values for each histogram.

  • Ylist (list) – A list of intensities for each histogram.

  • cmap (matplotlib.colormap) – The colormap used for shading intensities.

  • vmin (float) – Minimum intensity.

  • vmax (float) – float Maximum intensity.

  • Ylbls (list) – Optional. Label to place on each histogram. The default is [] where the axes are labeled normally with the first histogram numbered starting at 0.