matplotlib barchart фиксированное заполнение между внешним положением и положением - PullRequest
1 голос
/ 28 января 2020

Я пытаюсь создать диаграмму, которая всегда сохраняет фиксированное расстояние между внешним и внутренним положением, независимо от длины меток. Я хотел бы видеть bar и bar_long в той же позиции, что и bar_long и bar_perfect. Я пытался работать с axes.set_position (), но тщетно. Заранее благодарим за благодарную помощь!

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

Ответы [ 2 ]

0 голосов
/ 28 января 2020

Я бы не назвал это правильным решением, и мне немного стыдно даже публиковать его, но если вам действительно нужно что-то работать в это время ...

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

0 голосов
/ 28 января 2020

Чтобы все графики были одинаковыми, вам нужны одинаковые поля для всех. Итак, вам нужно установить их все на некоторое фиксированное значение. plt.subplots_adjust(...) делает это. Числа - это дроби от 0 до 1, где 0 - левый нижний угол рисунка, а 1 - верхний правый.

Для вашего примера 2x1 будет работать следующее:

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()
...