3

I have the following code for a 2x2 subplot:

figure(figsize=(10, 6), dpi=100)
plt.style.use('fivethirtyeight')

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
fig.tight_layout(pad=2)

fig.suptitle('Driving Relationships', fontsize=20)

# subplot 221
ax1.scatter(dataset2["duration"]/60, dataset2["distance"]/1000, c='red', alpha=0.5)
ax1.set_title("Duration vs Distance", fontsize=12)
ax1.set_xlabel("Duration (min)",fontsize=8)
ax1.set_ylabel("Distance (km)",fontsize=8)

# subplot 222
ax2.scatter(dataset2["duration"]/60, dataset2["speed_mean"], c='red', alpha=0.5)
ax2.set_title("Duration vs Speed", fontsize=12)
ax2.set_xlabel("Duration (min)",fontsize=8)
ax2.set_ylabel("Mean Speed (m/s)",fontsize=8)

# subplot 223
ax3.scatter(dataset2["ascent_total"], dataset2["acceleration_mean"], c='red', alpha=0.5)
ax3.set_title("Ascent vs Acceleration", fontsize=12)
ax3.set_xlabel("Ascent (m)",fontsize=8)
ax3.set_ylabel("Mean Acceleration (m/s^2)",fontsize=8)

# subplot 224
ax4.scatter(dataset2["descent_total"], dataset2["acceleration_mean"], c='red', alpha=0.5)
ax4.set_title("Descent vs Acceleration", fontsize=12)
ax4.set_xlabel("Descent (m)",fontsize=8)
ax4.set_ylabel("Mean Acceleration (m/s^2)",fontsize=8)

plt.show()

Despite my attempts to improve it, there are many overlappings as shown below: enter image description here

I've tried changing the figure size (nothing happened). I also used fig.tight_layour() not a major improvement even when setting padding values. How can I fix my code to have a more presentable figure?

4
  • 1
    Use constrained_layout instead of tight_layout Commented Aug 7, 2021 at 15:41
  • 2
    Also call tight_layout at the end, just before plt.show. Commented Aug 7, 2021 at 15:42
  • 1
    Thanks for posting a solution to your own question. If you're satisfied with your solution, you should consider posting it as an answer. Commented Aug 7, 2021 at 17:01
  • 1
    Does this answer your question? Improve subplot size/spacing with many subplots in matplotlib & this answer Commented Aug 7, 2021 at 22:08

2 Answers 2

5

Try to write it after your plots

plt.tight_layout()

Sign up to request clarification or add additional context in comments.

Comments

3

Apparently, for subplots changing the figure size is different. The following code did the job:

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 8))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.