1

I'm trying to create a barchart that keeps always a fixed distance between outer and inner position, regardless of the labels length. I would like to see bar and bar_long in the same position as bar_long and bar_perfect do. I've tried to work with axes.set_position(), but in vain. Thanks in advance for appreciated help!

import matplotlib.pyplot as plt

def createBar(figx, figy, labels):
    fig, ax = plt.subplots(figsize=(figx, figy)
    performance = [10, 70, 120]
    ax.barh(labels, performance)
    return fig
bar = createBar(2, 1, ('Tom', 'Dick', 'Fred'))
bar_long = createBar(2, 1, ('Tom Cruise', 'Dick & Doof', 'Fred Astaire'))
bar_perfect = createBar(2, 1, ('            Tom', 'Dick', 'Fred'))

enter image description here

Andrea
  • 2,932
  • 11
  • 23

2 Answers2

0

To get all plots the same, you need the same margins for all of them. So, you'll need to set them all to some fixed value. plt.subplots_adjust(...) does this. The numbers are fractions from 0 to 1, where 0 is the left bottom of the figure, and 1 the top right.

For your 2x1 example, the following would work:

import matplotlib.pyplot as plt

def createBar(figx, figy, labels):
    fig, ax = plt.subplots(figsize=(figx, figy))
    performance = [10, 70, 120]
    ax.barh(labels, performance)
    plt.subplots_adjust(left=0.4, right=0.95, top=0.97, bottom=0.25)
    return fig

bar = createBar(2, 1, ('Tom', 'Dick', 'Fred'))
bar_long = createBar(2, 1, ('Tom Cruise', 'Dick & Doof', 'Fred Astaire'))
bar_perfect = createBar(2, 1, ('            Tom', 'Dick', 'Fred'))

plt.show()
JohanC
  • 71,591
  • 8
  • 33
  • 66
0

I would not call it a proper solution, and I feel a bit ashamed to even post it, but if you really need something working in the meanwhile...

import matplotlib.pyplot as plt

def createBar(figx, figy, labels):
    fig, (ax0, ax) = plt.subplots(1, 2, figsize=(figx, figy),
                                  gridspec_kw={'width_ratios': [1, 2]})
    performance = [10, 70, 120]
    ax.barh(labels, performance)
    ax0.set_axis_off()

    return fig

bar = createBar(3, 1, ('Tom', 'Dick', 'Fred'))
bar_long = createBar(3, 1, ('Tom Cruise', 'Dick & Doof', 'Fred Astaire'))
bar_perfect = createBar(3, 1, ('          Tom', 'Dick', 'Fred'))

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Andrea
  • 2,932
  • 11
  • 23