Исправление функции маркировки гистограмм matplotlib - PullRequest
0 голосов
/ 02 мая 2020

Я хотел создать 2 гистограммы, состоящие из этих двух списков, и я его построил.

d_prime = [-0.53, -1.89, 0.76, 1.66]
d_prime_2 = [-0.69, 0.23, -0.88, 1.34]

plt.figure()
fig = plt.gcf()
fig.set_size_inches(11, 8)

times = ("1400", "2000", "3000", "4000")
ypos = np.arange(len(times))

plt.subplot(2,2,1)
bar_1= plt.bar(ypos, d_prime, align='center', alpha=0.5)
plt.title('First half of the D primes of subject {}'.format(i+3))
plt.xticks(x, index, rotation = 0)

plt.legend("D' primes 1st")

plt.subplot(2,2,2)
bar_2 = plt.bar(ypos, d_prime_2, align='center', alpha=0.5, color = 'cyan')
plt.title('Second half of the D primes of subject {}'.format(i+3))
plt.xticks(ypos, times)
plt.legend("D' primes 2nd")

def autolabel(rects):
    ##Attach a text label above each bar in *rects*, displaying its height.
    for rect in rects:
        height = rect.get_height()
        plt.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

autolabel(bar_1)
autolabel(bar_2)
plt.show()

Я пытался сделать это, но это выглядит так:

enter image description here

Я хочу четко обозначить bar_1 и bar_2, но он помечает только bar_2.

Можете ли вы помочь мне исправить эту функцию или вы предлагаете какие-либо функции для этого?

1 Ответ

1 голос
/ 02 мая 2020

Проблема возникает из-за того, что вторым подзаговором являются активные оси.

Быстрое исправление, которое не сильно меняет код, заключалось бы в добавлении параметра в autolabel для осей:

ax1 = plt.subplot(2,2,1)
...
ax2 = plt.subplot(2,2,2)
...
def autolabel(ax, rects):
    ...
    ax.annotate(...)

autolabel(ax1, bar1)
autolabel(ax2, bar2)

Или просто определите функцию autolabel перед отображением гистограмм и вызовите эту функцию внутри каждого оператора подзаговора.

def autolabel(rects):
    ...

...
plt.subplot(1,2,1)
bar_1 = ...
autolabel(bar_1)  # add annotations on the first subplot (the active one)

plt.subplot(1,2,2)  # now the current axes is the second one
bar_2 = ...
autolabel(bar_2)  # add annotations on the second subplot
...