Issue
I have created 3 horizontal bar charts with these codes. As you can see the spacing between y-labels is quite uniform on all charts because the height of each figure was customized independently.
import matplotlib.pyplot as plt
import numpy as np
xa = np.arange(1, 15)
xb = np.arange(1, 30)
xc = np.arange(1, 5)
ya = [f'label{ea}' for ea in xa]
yb = [f'label_blablabla{ea}' for ea in xb]
yc = [f'label_abcx{ea}' for ea in xc]
plt.figure(figsize=(5, len(xa)*.3))
plt.barh(ya, xa)
plt.figure(figsize=(5, len(xb)*.3))
plt.barh(yb, xb)
plt.figure(figsize=(5, len(xc)*.3))
plt.barh(yc, xc)
plt.show()
But these figures do not line up horizontally because the text of the y-labels has different lengths. So I use subplots to align the figures as follows:
import matplotlib.pyplot as plt
import numpy as np
xa = np.arange(1, 15)
xb = np.arange(1, 30)
xc = np.arange(1, 5)
ya = [f'label{ea}' for ea in xa]
yb = [f'label_blablabla{ea}' for ea in xb]
yc = [f'label_abcx{ea}' for ea in xc]
fig, axs = plt.subplots(3, 1, figsize=(5, 10))
axs[0].barh(ya, xa)
axs[1].barh(yb, xb)
axs[2].barh(yc, xc)
plt.show()
But then this technique messed up the spacing between y-labels in each subplot. Does anyone have better ideas to make the spacing between y-labels uniform on all subplots like the first image?
Solution
Add gridspec_kw={'height_ratios': [len(xa), len(xb), len(xc)]}
to initialize the subplots.
import matplotlib.pyplot as plt
import numpy as np
xa = np.arange(1, 15)
xb = np.arange(1, 30)
xc = np.arange(1, 5)
ya = [f'label{ea}' for ea in xa]
yb = [f'label_blablabla{ea}' for ea in xb]
yc = [f'label_abcx{ea}' for ea in xc]
fig, axs = plt.subplots(3, 1, figsize=(5, 10), gridspec_kw={'height_ratios': [len(xa), len(xb), len(xc)]})
axs[0].barh(ya, xa)
axs[1].barh(yb, xb)
axs[2].barh(yc, xc)
output:
NB. The result will not be perfectly even (like in your first solution) as the heights include the axis labels and eventual titles. But the higher the number of rows per graph and lower the differences, the more it will converge towards the ideal value.
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.