x label is outside of my figure because of figsize

Viewed 179

I am constructing a simple graph with the following code:

    plt.figure(figsize=(7, 3))
    plt.plot(idl_t, idl_q, color="blue", lw=2)
    plt.plot(dsc_t, dsc_q, color="red", lw=2)
    plt.plot(cha_t, cha_q, color="green", lw=2)
    plt.xlabel("Time (hour)")
    plt.show()

with input data as following:

    idl_t, idl_q = [[0, 20], [8, 24]], [[100, 100], [100, 100]]
    dsc_t, dsc_q = [[8, 14], [12, 18]], [[100, 100], [5, 5]]
    cha_t, cha_q = [[12, 18], [14, 20]], [[5, 5], [100, 100]]

However, the code somehow cuts the x-label on figure as below: wrong graph

I am pretty sure it is because of changing the figsize and seems that that it allocates label space proportionally to it. See the normal figsize figure below: right graph

How can I preserve enough space for xlabel with different figsizes? And is it actually supposed to be like this as it seems as a bug for me?

I would highly appreciate your advice!

EDIT 1:

Thank you all for your replies. Although I have chosen tight_layout as a better solution I would definitely suggest you using a method proposed by Jody Klymak. Please find his implementation in the answers below!

2 Answers

Use constrained_layout. It is more flexible than tight_layout (usually):

import matplotlib.pyplot as plt 

idl_t, idl_q = [[0, 20], [8, 24]], [[100, 100], [100, 100]]
dsc_t, dsc_q = [[8, 14], [12, 18]], [[100, 100], [5, 5]]
cha_t, cha_q = [[12, 18], [14, 20]], [[5, 5], [100, 100]]

fig, ax = plt.subplots(figsize=(7, 3), constrained_layout=True)
ax.plot(idl_t, idl_q, color="blue", lw=2)
ax.plot(dsc_t, dsc_q, color="red", lw=2)
ax.plot(cha_t, cha_q, color="green", lw=2)
ax.set_xlabel("Time (hour)")
plt.show()

enter image description here

Use plt.tight_layout

plt.figure(figsize=(7, 3), )
plt.plot(idl_t, idl_q, color="blue", lw=2)
plt.plot(dsc_t, dsc_q, color="red", lw=2)
plt.plot(cha_t, cha_q, color="green", lw=2)
plt.xlabel("Time (hour)")
plt.tight_layout()  # <- HERE
plt.show()

enter image description here

Related