Eerik Sven Puudist
Eerik Sven Puudist

Reputation: 2346

Matplotlib figure proportions are off when saved to PDF

Using the following code

import matplotlib.pyplot as plt
import seaborn as sns

plt.rc('axes', labelsize=12)

messages_data = messages_db_response.DataFrame()

fig, axd = plt.subplot_mosaic([["a", "b"],
                               ["c", "d"]])
axd["a"].set_xlabel("score")
axd["b"].set_xlabel("score")
axd["c"].set_xlabel("last activity")
axd["d"].set_xlabel("last activity")

axd["a"].set_ylabel("curricular messages count")
axd["b"].set_ylabel("extracurricular messages count")
axd["c"].set_ylabel("curricular messages count")
axd["d"].set_ylabel("extracurricular messages count")

sns.scatterplot(ax=axd["a"], data=messages_data, x="score", y="curricular_msg_count", hue="grade")
sns.scatterplot(ax=axd["b"], data=messages_data, x="score", y="extracurricular_msg_count", hue="grade")
sns.scatterplot(ax=axd["c"], data=messages_data, x="last_activity", y="curricular_msg_count", hue="grade")
sns.scatterplot(ax=axd["d"], data=messages_data, x="last_activity", y="extracurricular_msg_count", hue="grade")

axd["a"].set_ybound(0, 350)
axd["c"].set_ybound(0, 300)
axd["b"].set_ybound(0, 600)
axd["d"].set_ybound(0, 600)

I generated the following figure in the Jupyter notebook:

However, when I saved it to a PDF (extracted the code to a standalone Python script and added a call to plt.savefig()), I got a result with totally messed up proportions:

I already added a call to plt.tight_layout(), without that the result was even worse. I also tried to add sns.set_context("paper"), but that did not make any difference.

How can I get the PDF to look like the image from the Jupyter notebook?

Upvotes: 1

Views: 197

Answers (1)

Eerik Sven Puudist
Eerik Sven Puudist

Reputation: 2346

You need to specify the size of the figure explicitly. plot() and savefig() have different default values which can mess things up.

Simply add fig.set_size_inches(9, 6, forward=True) and the two versions will start to look the same.

If you try to save it in some other format, there are a few other settings which might be explicitly set, see this answer for deatils.

Upvotes: 1

Related Questions