Matplotlib - subplots
The code below says it all really. Oh, and it's using Pandas to read in Compton scattering experiment data. The glob thing is a nice way of geting all the CSV files in a directory.
import glob
import math as mt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Set the number of subplot columns
NUMBER_OF_COLUMNS = 2
# Find all CVS files in this directory
files = glob.glob('ComptonData/*.csv')
# For testing this removes the last file leaving an odd number
files=files[:-1]
# Read them into a list of DataFrames
df_list=[]
for file in files:
df_ = pd.read_csv(file)
df_list.append(df_)
# Do the plots with n_cols columns
n_cols = NUMBER_OF_COLUMNS
n_rows = mt.ceil(len(files)/n_cols)
# We'll have a common x scale but differet y scales
fig, axs = plt.subplots(nrows=n_rows, ncols=n_cols, sharex=True, sharey=False, figsize=(10,7.5))
# Iterate through the file list we've just generated and append the sub-plots
# I've chosen to just include the 'interesting' part of the data that includes Ka and Kb peaks.
for k, df in enumerate(df_list):
x = df['Channel'][200:350]
y = df['Counts'][200:350]
# Generate some label text for later
angle = df.at[0,'Value']
label = 'Scattering angle = '+ str(int(angle))
# These next 2 lines generate row, col pairs from the index, k
col = k%n_cols
row = (int(k/n_cols)%max(n_rows,n_cols))
axs[row,col].plot(x,y)
axs[row,col].grid()
# Put a label in each subplot near top left
axs[row,col].text(0.05, 0.85, label, transform=axs[row,col].transAxes, fontsize=7)
# This removes the last 'blank' sub-plots caused by odd number of plots
# AND makes sure you've got an x -axis label on all bottom plots
if len(df_list)%n_cols != 0: #An 'odd' number of plots
blank_plots = n_cols-(len(df_list)%n_cols)
for i in range(blank_plots):
axs[n_rows-2,n_cols-(i+1)].xaxis.set_tick_params(which='both', labelbottom=True, labeltop=False)
# Remove the redundant sub-plot
fig.delaxes(axs[n_rows-1,n_cols-(i+1)])
# Now generate an overall, encompassing 'axes' plot for aggregate labels
ax = fig.add_subplot(111, frameon=False)
# Give this some common x and y labels. Use the argument `labelpad` to move label downwards.
ax.set_xlabel('Channel number', fontsize=14, fontweight='bold', fontstyle='italic', labelpad=25)
ax.set_ylabel('Counts', fontsize=14, fontweight='bold', labelpad=35)
# But we don't want it to have any axis 'ticks'/values
ax.set_yticklabels([])
ax.set_xticklabels([])
# Show them
plt.tight_layout()
plt.show()