水平堆叠的条形图值未正确对齐

时间:2019-02-14 16:49:08

标签: python matplotlib charts label

我是Python的新手,并且正在使用该语言。我已经搜索了上周的解决方案,但没有成功。

我有一个水平堆叠的条形图,我无法使标签正确放置自己。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
plt.rcParams['figure.figsize'] = 25,12

fig = plt.figure()
ax = plt.subplot()


respond = [2, 19, 46, 46, 55, 61, 78, 121, 150, 158, 169]
no_response = [0, 3, 51, 70, 32, 19, 61, 81, 109, 105, 132]
y = np.arange(len(respond))

plt.barh(y, respond, color='teal')
plt.barh(y, no_response, color='brown', left=respond)

y_labels = ['label_1', 'Label_2', 'Label_3', 'Label_4', 'Label_5',
        'Label_6', 'Label_7', 'Label_8', 'Label_9', 'Label_10', 
'Label_11']
plt.yticks(y, y_labels)
plt.title('MASS Responses by Group')
plt.xlabel('Responses')
plt.ylabel('GD Group')

responding = mpatches.Patch(color='teal', label='Responded')
not_responding = mpatches.Patch(color='brown', label='No Response')
plt.legend(handles=[responding, not_responding], loc='lower right')

rects = ax.patches

# For each bar: Place a label
for rect in rects:
    # Get X and Y placement of label from rect.
    x_value = rect.get_width()
    y_value = rect.get_y() + rect.get_height()/2.5

    # Number of points between bar and label. Change to your liking.
    space = 25
    # Vertical alignment for positive values
    ha = 'center'

    # If value of bar is negative: Place label left of bar
    if x_value < 0:
        # Invert space to place label to the left
        space *= -1
        # Horizontally align label at right
        ha = 'center'

    # Use X value as label and format number with one decimal place
    label = "{:.0f}".format(x_value)

    # Create annotation
    ax.annotate(
        label,                      # Use `label` as label
        (x_value, y_value),         # Place label at end of the bar
        xytext=(space, 0),          # Horizontally shift label by `space`
        textcoords="offset points", # Interpret `xytext` as offset in points
        va='baseline',              # Vertically center label
        ha='center',                # Horizontally align label differently 
         for positive and negative values.
        color='white',              # Font color of the label
        fontweight='bold')          # Bolded                      

#fig.savefig('test.png', bbox_inches='tight', pad_inches=2)
plt.show()

运行图表时,您可以看到这些值相对于X轴值对齐。我需要它们与各自的矩形条对齐。

example

0 个答案:

没有答案