Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Frequency used subplot coding for me to use.
"""Frequency used matplotlib subplot."""
import math
import numpy as np
import matplotlib.pyplot as plt
# Apply plot function into all data in Xs dictionary.
def subplots(Xs, plot_func):
# Set subplots location info
n_cols = 4
n_rows = math.ceil(len(Xs) / n_cols)
figsize = (3 * n_cols, 3 * n_rows)
# Create ax
fig, axes = plt.subplots(ncols=n_cols, nrows=n_rows, figsize=figsize)
# Plot
for ax, (key, dt) in zip(axes.ravel(), Xs.items()):
ax = plot_func(ax, dt)
ax.set_title(key)
# Figure configure
fig.tight_layout()
fig.subplots_adjust(top=0.85)
fig.suptitle('main title')
# Define plot function what ever you like
def get_hist_plot_func(plot_args):
def hist_plot_func(ax, xs):
r = ax.hist(xs, **plot_args)
return ax
return hist_plot_func
def main():
# Make toy data with multiple columns
n_samples = 100
Xs = {}
for key in ('key1', 'key2', 'key3', 'key4'):
Xs[key] = np.random.normal(size=n_samples)
# Build function to plot histogram
plot_args = {'bins': 10}
hist_plot_func = get_plot_func(plot_args)
# plot
subplots(Xs, hist_plot_func)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.