1

I'm using code much like:

import matplotlib.pyplot as plt

labels = ['AAA', 'BBBBBBBBBBBBB', 'CCCCCC', 'DDDDDDDDDD']
values = [0, 2, 2, 5]
fig, ax = plt.subplots(figsize=(8, 0.07 + 0.25 * len(values)))
bars = ax.barh(labels, values, color=colors)

to generate horizontal bar plots as separate figures, one after another:

barh

How can I make the left spines (i.e. the black bars) align when the width of labels varies between plots? (Aside from just aligning the rendered images to the right.)

I think the left margin/padding/space should be fixed, or the bar width should be fixed, but I can't quite figure how to do it.

tdy
  • 36,675
  • 19
  • 86
  • 83
Minty
  • 78
  • 1
  • 7
  • Would using `sharex` like [this](https://stackoverflow.com/questions/42973223/how-to-share-x-axes-of-two-subplots-after-they-have-been-created) be what you are looking for? – busybear Feb 14 '23 at 18:24
  • @busybear this works, but requires using a singular figure. I'm afraid I need these to be separate figures. – Minty Feb 14 '23 at 18:37
  • `plt.subplots_adjust(left=0.2)` would set the white space at the left to 20% of the figure width. (If you use `plt.savefig()` you should avoid `bbox_inches='tight'`. In Jupyter, `bbox_inches='tight'` happens automatically) – JohanC Feb 14 '23 at 19:01

1 Answers1

1

In these cases, I just add empty axes at the left edge of each figure. I'm sure there are more sophisticated ways, but I find this to be simplest:

  • fig1 with blank axes at left location
    fig1, ax = plt.subplots(figsize=(8, 1))
    ax.barh(['AAA', 'BBBBBBBBBBBBB', 'CCCCCC', 'DDDDDDDDDD'], [0, 2, 2, 5])
    
    # add empty axes at `left` location (unit: fraction of figure width)
    left = -0.05  # requires manual adjustment
    fig1.add_axes([left, 0, 0, 0.01]).axis('off')
    
    plt.show()
    
  • fig2 with blank axes at same left location as fig1
    fig2, ax = plt.subplots(figsize=(8, 1))
    ax.barh(['AAaaaA', 'BBBB', 'CCCCCC', 'DDDDD'], [2, 8, 7, 1])
    
    # add empty axes at same `left` location as fig1
    fig2.add_axes([left, 0, 0, 0.01]).axis('off')
    
    plt.show()
    

Output of fig1 and fig2:


A similar approach would be to annotate a space character at the left of each figure:

ax.annotate(' ', (left, 0), xycoords='axes fraction', annotation_clip=False)
tdy
  • 36,675
  • 19
  • 86
  • 83