I need to combine catplot subfigures into a single figure and then save that figure to a file. I used plt.subplots
to create independent axis for each subfigure and then assigned the catplots to the subfigures. The figure looks fine in a Jupyter notebook (see here), but when I check the stored file I see a blank figure with two subplots (see blank figure). I reviewed related posts (see here and there), but their focus is not in storing the produced figure. I wonder what I can do store a single file with the figure containing both catplot subfigures. Please see my reproducible code below along with datasets here (df1 and df2). I used pandas
version 1.2.3, matplotlib
version 3.3.4, and seaborn
version 0.11.0.
Thanks in advance.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Read data
df1 = pd.read_csv("df1.csv")
df2 = pd.read_csv("df2.csv")
# Setup subfigures
fig, axs = plt.subplots(2, 1, figsize=(10, 7))
category_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# Top subfigure
g = sns.catplot(x="Month", hue="Day of Week", kind="count", data=df1, hue_order=category_order, legend=False, aspect=20/8, ax=axs[0])
# Annotate bars
ax[0] = g.facet_axis(0, 0)
for p in ax[0].patches:
ax[0].text(p.get_x(),
p.get_height()*1.02,
f"{p.get_height():.0f}",
color="black",
rotation="horizontal",
size="small")
# Formatting
g.tight_layout()
g.set(ylim=(0, 18))
sns.despine(ax=ax[0], top=False, right=False)
# Bottom subfigure
g = sns.catplot(x="Month", hue="Day of Week", kind="count", data=df2, hue_order=category_order, legend=True, aspect=20/8, ax=axs[1])
# Annotate bars
ax[1] = g.facet_axis(0, 0)
for p in ax[1].patches:
ax[1].text(p.get_x(),
p.get_height()*1.02,
f"{p.get_height():.0f}",
color="black",
rotation="horizontal",
size="small")
# Formatting
g.tight_layout()
g.set(ylim=(0, 18))
sns.despine(ax=ax[1], top=False, right=False)
g.set_xlabels("Date")
# Close blank figure
plt.close(1)
fig.savefig("fig.pdf", dpi=200, bbox_inches="tight")
plt.show()