Commit 953e090b authored by Parish, Chad's avatar Parish, Chad
Browse files

Error trap MPL versions

parent 809870fe
Loading
Loading
Loading
Loading
+0 −8
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

# Don't use vendor exports naively
<br>
Vendor software usually allows graphics exports. However, there are often subtleties in the vendor-formatted graphics that make them less than ideal for placement into presentations or papers. We show some examples here of vendor-formatted graphics compared to replotted versions.

%% Cell type:markdown id: tags:

Imports:

%% Cell type:code id: tags:

``` python
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
os.chdir('./vendor')


# this is not a standard Anoconda Python package, but it's very useful.
try:
    from matplotlib_scalebar.scalebar import ScaleBar
    scalebar_imported = True
except:
    print('Please install matplotlib-scalebar')
    scalebar_imported = False
```

%% Output

    3.0.1

%% Cell type:code id: tags:

``` python
import matplotlib

if matplotlib.__version__.split('.')[0] < '3':
    raise ImportError('Requires matplotlib 3.0.0 or higher')
```

%% Output

    True

%% Cell type:markdown id: tags:

### In this case, the vendor also exports the data as an Excel file
The Python `pandas` library allows easy import of Excel. The variable `df` is a Pandas dataframe.

%% Cell type:code id: tags:

``` python
df = pd.read_excel('spectrum_out.xls', skiprows=24)
df.head()
```

%% Output

       Channel    Energy  Counts  Unnamed: 3  Unnamed: 4
    0        0 -0.949805     0.0         NaN         NaN
    1        1 -0.939806     0.0         NaN         NaN
    2        2 -0.929807     0.0         NaN         NaN
    3        3 -0.919808     0.0         NaN         NaN
    4        4 -0.909809     0.0         NaN         NaN

%% Cell type:markdown id: tags:

Reformat the data:

%% Cell type:code id: tags:

``` python
X = df['Energy'].values
X_range = (X < 20) & (X > 0.1)  # discard data > 20 keV and < 0.1 keV
X = X[X_range]
Y = df['Counts'].values[X_range]
```

%% Cell type:markdown id: tags:

Set up the X-ray lines to label. This could easily be stored in an HDF5 file for simple lookup, rather than typed in manually:

%% Cell type:code id: tags:

``` python
x_ray_dict = {r'$O K\alpha$': 0.525, r'$Ga L\alpha$': 1.09,
             r'$Mo K\alpha$': 17.48, r'$W L\alpha$': 8.40, r'$W L\beta$': 9.67,
              r'$W L\gamma$': 11.29, r'$W M\alpha$': 1.8}
```

%% Cell type:markdown id: tags:

### Replot the data

%% Cell type:code id: tags:

``` python
with plt.style.context(({'font.sans-serif': 'Arial', 'font.weight': 'bold',
              'axes.labelsize': 20, 'xtick.labelsize': 18,
               'ytick.labelsize': 18, 'svg.fonttype': 'none'})):
    fig, ax = plt.subplots(figsize=(13,5))
    ax.plot(X, Y, color='k')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.set_xlabel('X-ray energy, keV')
    ax.set_ylabel('X-ray counts')
    Y_max = Y.max()
    ax.set_ylim(top=Y_max * 1.2)
    ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useMathText=True)

with plt.style.context({'text.usetex': 'true'}):
    for i in x_ray_dict.items():
        X_index = np.abs(X-i[1]).argmin()
        Y_val = Y[X_index]
        ax.annotate(i[0], xy=(i[1], Y_val), xytext=(i[1]-0.6, (Y_val + (0.15)*Y_max)),
                    fontsize=14, fontweight='bold', arrowprops=dict(arrowstyle='->'))

fig.tight_layout()
fig.savefig('../EDS_outout_spec.svg')
fig.savefig('../EDS_output_spec.png', dpi=300)
```

%% Output


%% Cell type:markdown id: tags:

### Now, what about exported images, rather than simple (x,y) data?
For quantitative information, such as X-ray intensity maps here, you need to be careful about intensity scaling.

%% Cell type:code id: tags:

``` python
W = plt.imread('16bit-export_W-LA.tif')
Re = plt.imread('16bit-export_Re-LA.tif')
Os = plt.imread('16bit-export_Os-LA.tif')
fig_list = [W, Re, Os]
name_list = ['W', 'Re', 'Os']
im_size = 157
im_unit = 'nm'
```

%% Cell type:markdown id: tags:

This simple script will perform nearest-neighbor binning to improve the signal to noise in the figures.

%% Cell type:code id: tags:

``` python
downsampled_figs = []
inc = 2
for i in fig_list:
    (xx, yy) = i.shape
    new_i = np.zeros(shape=(xx//inc, yy//inc))
    for a in range(0, xx, inc):
        for b in range(0, yy, inc):
            new_i[a//inc, b//inc] = (i[a:a+inc, b:b+inc]).sum()
    downsampled_figs.append(new_i)
```

%% Cell type:markdown id: tags:

### Here, we create the figures with quantitative color bars.

%% Cell type:code id: tags:

``` python
fig = plt.figure(figsize=(9, 4.3))
ax = [fig.add_subplot(1,3,i+1) for i in range(3)]  # set up subplots_adjust below

with plt.style.context({'font.sans-serif': 'Arial', 'svg.fonttype': 'none'}):
    for i, im in enumerate(downsampled_figs):
        # vmin=0 forces the color scale to start at zero, and im.max() for vmax scales each
        # image individually.
        P = ax[i].imshow(im, cmap='viridis', vmin=0, vmax=im.max())
        ax[i].axis('off')
        C = plt.colorbar(P, ax=ax[i], orientation='horizontal', shrink=0.55)
        C.ax.tick_params(labelsize=14)
        C.ax.set_in_layout(False)
        ax[i].set_aspect(1)
        ax[i].set_title(name_list[i])

    if scalebar_imported is True:  # add scalebar to left image.
        sc = ScaleBar(im_size / im.shape[0], im_unit, length_fraction=0.3, location='lower right')
        ax[0].add_artist(sc)

    fig.subplots_adjust(wspace=0, hspace=0)  # pack them closer

    fig.savefig('../vendor_colorbar.png', dpi=300, bbox_inches='tight')
    fig.savefig('../vendor_colorbar.svg', dpi=300, bbox_inches='tight')
```

%% Output


%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
```