Reputation: 158
I am constructing a simple graph with the following code:
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]]
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()
However, the code somehow cuts the x-label on figure as below:
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:
How can I preserve enough space for xlabel
with different figsize
s? And is it actually supposed to be like this as it seems as a bug for me?
Upvotes: 3
Views: 2288
Reputation: 120439
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()
Update
As suggested by @TrentonMcKinney, you can also pass tight_layout=True
as parameter of plt.figure
plt.figure(figsize=(7, 3), tight_layout=True)
Upvotes: 3
Reputation: 5913
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()
Upvotes: 2