\(\renewcommand\AA{\unicode{x212B}}\)

Matplotlib in Mantid

Other Plotting Documentation

Help Documentation

Introduction

Mantid can now use Matplotlib to produce figures. There are several advantages of using this software package:

  • it is python based, so it can easily be incorporated into Mantid scripts

  • there is a large user community, and therefore excellent documentation and examples are available

  • it is easy to change from plotting on the screen to produce publication quality plots in various image formats

While Matplotlib is using data arrays for inputs in the plotting routines, it is now possible to also use several types on Mantid workspaces instead. For a detailed list of functions that use workspaces, see the documentation of the mantid.plots module.

This page is intended to provide examples about how to use different Matplotlib commands for several types of common task that Mantid users are interested in.

To understand the matplotlib vocabulary, a useful tool is the “anatomy of a figure”, also shown below.

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Here are some of the highlights:

  • Figure is the main container in matplotlib. You can think of it as the page

  • Axes is the coordinate system. It contains most of the figure elements, such as Axis, Line2D, Text. One can have multiple Axes objects in one Figure

  • Axis is the container for the ticks and labels for the x and y axis of the plot

Showing/saving figures

There are two main ways that one can visualize images produced by matplotlib. The first one is to pop up a window with the required graph. For that, we use the show() function of the figure.

import matplotlib.pyplot as plt
fig,ax=plt.subplots()
#some code to generate figure
fig.show()

If one wants to save the output, the figure object has a function called savefig. The main argument of savefig is the filename. Matplotlib will figure out the format of the figure from the file extension. The ‘png’, ‘ps’, ‘eps’, and ‘pdf’ extensions will work with almost any backend. For more information, see the documentation of Figure.savefig Just replace the code above with:

import matplotlib.pyplot as plt
fig,ax=plt.subplots()
#some code to generate figure
fig.savefig('plot1.png')
fig.savefig('plot1.eps')

Sometimes one wants to save a multi-page pdf document. Here is how to do this:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages('/home/andrei/Desktop/multipage_pdf.pdf') as pdf:
    #page1
    fig,ax=plt.subplots()
    ax.set_title('Page1')
    pdf.savefig(fig)
    #page2
    fig,ax=plt.subplots()
    ax.set_title('Page2')
    pdf.savefig(fig)

Simple plots

For matrix workspaces, if we use the mantid projection, one can plot the data in a similar fashion as the plotting of arrays in matplotlib. Moreover, one can combine the two in the same figure

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Some data should be visualized as two dimensional colormaps

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

One can then change properties of the plot. Here is an example that changes the label of the data, changes the label of the x and y axis, changes the limits for the y axis, adds a title, change tick orientations, and adds a grid

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Let’s create now a figure with two panels. In the upper part we show the workspace as above, but we add a fit, In the bottom part we add the difference.

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

One can do twin axes as well:

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Custom Colors

Custom Color Cycle (Line / 1D plots)

The Default Color Cycle doesn’t have to be used. Here is an example where a Custom Color Cycle is chosen. Make sure to fill the list custom_colors with either the HTML hex codes (eg. #b3457f) or recognised names for the desired colours. Both can be found online.

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Custom Colormap (MantidWorkbench)

You can view the premade Colormaps here. These Colormaps can be registered and remain for the current session, but need to be rerun if Mantid has been reopened. Choose the location to Save your Colormap file wisely, outside of your MantidInstall folder!

The following methods show how to Load, Convert from MantidPlot format, Create from Scratch and Visualise a Custom Colormap.

  • If you already have a Colormap file in an (N by 4) format, with all values between 0 and 1, then use:

1a. Load Colormap and Register

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

Cmap_Name = 'Beach' # Colormap name
Loaded_Cmap = np.loadtxt("C:\Path\to\File\Filename.txt")
# Register the Loaded Colormap
Listed_CustomCmap = ListedColormap(Loaded_Cmap, name=Cmap_Name)
plt.register_cmap(name=Cmap_Name, cmap= Listed_CustomCmap)

# Create and register the reverse colormap
Res = len(Loaded_Cmap)
Reverse = np.zeros((Res,4))
for i in range(Res):
  for j in range(4):
      Reverse[i][j] = Loaded_Cmap[Res-(i+1)][j]

Listed_CustomCmap_r = ListedColormap(Reverse, name=(Cmap_Name + '_r') )
plt.register_cmap(name=(Cmap_Name + '_r'), cmap= Listed_CustomCmap_r)
  • If you have a Colormap file in a Mantid format (N by 3) with all values between 0 and 255, firstly rename the file extension from .map to .txt, then use:

1b. Convert Mantid Colormap and Register

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

Cmap_Name = 'Beach'
Loaded_Cmap = np.loadtxt("/Path/to/file/Beach.txt")

Res = len(Loaded_Cmap)
Cmap = np.zeros((Res,4))
for i in range(Res):
  '''Normalise RGB values, Add 4th column alpha set to 1'''
  for j in range(3):
    Cmap[i][j] = float(Loaded_Cmap[i][j]) / 255
  Cmap[i][3] = 1
  '''Checks all values b/w 0 and 1'''
  for j in range(4):
      if Cmap[i][j] > 1:
          print(Cmap[i])
          raise ValueError('Values must be between 0 and 1, one of the above is > 1')
      if Cmap[i][j] < 0:
          print(Cmap[i])
          raise ValueError('Values must be between 0 and 1, one of the above is negative')
      else:
          pass

#np.savetxt("C:\Path\to\File\Filename.txt",Cmap) #uncomment to save to file

# Register the Loaded Colormap
Listed_CustomCmap = ListedColormap(Cmap, name=Cmap_Name)
plt.register_cmap(name=Cmap_Name, cmap= Listed_CustomCmap)

# Create and register the reverse colormap
Reverse = np.zeros((Res,4))
for i in range(Res):
  for j in range(4):
      Reverse[i][j] = Cmap[Res-(i+1)][j]

Listed_CustomCmap_r = ListedColormap(Reverse, name=(Cmap_Name + '_r') )
plt.register_cmap(name=(Cmap_Name + '_r'), cmap= Listed_CustomCmap_r)
  • To Create a Colormap from scratch, use:

1c. Create and Register

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import numpy as np

Cmap_Name = 'Beach' # Colormap name
Res = 500 # Resolution of your Colormap (number of steps in colormap)

Re = Res-1
Cmap = np.zeros((Res,4))
for i in range(Res):
  '''Input functions inside float(), Divide by Res to normalise'''
  Cmap[i][0] = float(Res)   / Res       #Red   #just 1
  Cmap[i][1] = float(i)     / Re        #Green #+ve i divisible by Res-1 = Re
  Cmap[i][2] = float(Res-i)**2 / Res**2 #Blue  #Make sure Norm_factor correct
  Cmap[i][3] = 1
  '''Checks all values b/w 0 and 1'''
  for j in range(4):
      if Cmap[i][j] > 1:
          print(Cmap[i])
          raise ValueError('Values must be between 0 and 1, one of the above is > 1')
      if Cmap[i][j] < 0:
          print(Cmap[i])
          raise ValueError('Values must be between 0 and 1, one of the above is Negative')
      else:
          pass

#np.savetxt("C:\Path\to\File\Filename.txt",Cmap) #uncomment to save to file

Listed_CustomCmap = ListedColormap(Cmap, name = Cmap_Name)
plt.register_cmap(name = Cmap_Name, cmap = Listed_CustomCmap)

# Create and register the reverse colormap
Reverse = np.zeros((Res,4))
for i in range(Res):
  for j in range(4):
      Reverse[i][j] = Cmap[Res-(i+1)][j]

Listed_CustomCmap_r = ListedColormap(Reverse, name=(Cmap_Name + '_r') )
plt.register_cmap(name=(Cmap_Name + '_r'), cmap= Listed_CustomCmap_r)

Now the Custom Colormap has been registered, right-click on a workspace and produce a colorfill plot. In Figure Options (Gear Icon in Plot Figure), under the Images Tab, you can use the drop down-menu to select the new Colormap, and use the check-box to select its Reverse!

  • Otherwise, use a script like this (from above in Section “Simple Plots”) to plot with your new Colormap:

2. Plot New Colormap (change the “cmap” name in line 12 accordingly)

from mantid.simpleapi import Load, ConvertToMD, BinMD, ConvertUnits, Rebin
from mantid import plots
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
data = Load('CNCS_7860')
data = ConvertUnits(InputWorkspace=data,Target='DeltaE', EMode='Direct', EFixed=3)
data = Rebin(InputWorkspace=data, Params='-3,0.025,3', PreserveEvents=False)
md = ConvertToMD(InputWorkspace=data,QDimensions='|Q|',dEAnalysisMode='Direct')
sqw = BinMD(InputWorkspace=md,AlignedDim0='|Q|,0,3,100',AlignedDim1='DeltaE,-3,3,100')

fig, ax = plt.subplots(subplot_kw={'projection':'mantid'})
c = ax.pcolormesh(sqw, cmap='Beach', norm=LogNorm())
cbar=fig.colorbar(c)
cbar.set_label('Intensity (arb. units)') #add text to colorbar
#fig.show()
../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Colormaps can also be created with the colormap package or by concatenating existing colormaps.

Plotting Sample Logs

The mantid.plots.MantidAxes.plot function can show sample logs. By default, the time axis represents the time since the first proton charge pulse (the beginning of the run), but one can also plot absolute time using FullTime=True

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Note that the parasite axes in matplotlib do not accept the projection keyword. So one needs to use mantid.plots.axesfunctions.plot instead.

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

If a TimeROI is applied to the workspace, the Sample Logs can also include shaded regions to indicate the regions of the logs that are being excluded by the TimeROI.

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Complex plots

One common type of a slightly more complex figure involves drawing an inset.

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Plotting dispersion curves on multiple panels can also be done using matplotlib:

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

Change Matplotlib Defaults

It is possible to alter the default appearance of Matplotlib plots, e.g. linewidths, label sizes, colour cycles etc. This is most readily achieved by setting the rcParams at the start of a Mantid Workbench session. The example below shows a plot with the default line width, followed be resetting the parameters with rcParams. An example with many of the editable parameters is available at the Matplotlib site.

../_images/ImageNotFound.png

Enable :plots: using DOCS_PLOTDIRECTIVE in CMake

For much more on customising the graph appearance see the Matplotlib documentation.

A list of some common properties you might want to change and the keywords to set:

Parameter

Keyword

Default

Error bar cap

errorbar.capsize

0

Line width

lines.linewidth

1.25

Grid on/off

axes.grid

False

Ticklabel size

xtick.labelsize ytick.labelsize

medium

Minor ticks on/off

xtick.minor.visible ytick.minor.visible

False

Face colour

axes.facecolor

white

Font type

font.family

sans-serif

A much fuller list of properties is avialble in the Matplotlib documentation.