복붙노트

[PYTHON] pyplot.barh ()로 각 막대의 막대 값을 표시하는 방법?

PYTHON

pyplot.barh ()로 각 막대의 막대 값을 표시하는 방법?

막대 그래프를 생성했습니다. 막대의 값을 각 막대에 어떻게 표시 할 수 있습니까?

현재 플롯 :

내가 얻으려고하는 것 :

내 코드 :

import os
import numpy as np
import matplotlib.pyplot as plt

x = [u'INFO', u'CUISINE', u'TYPE_OF_PLACE', u'DRINK', u'PLACE', u'MEAL_TIME', u'DISH', u'NEIGHBOURHOOD']
y = [160, 167, 137, 18, 120, 36, 155, 130]

fig, ax = plt.subplots()    
width = 0.75 # the width of the bars 
ind = np.arange(len(y))  # the x locations for the groups
ax.barh(ind, y, width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(x, minor=False)
plt.title('title')
plt.xlabel('x')
plt.ylabel('y')      
#plt.show()
plt.savefig(os.path.join('test.png'), dpi=300, format='png', bbox_inches='tight') # use format='svg' or 'pdf' for vectorial pictures

해결법

  1. ==============================

    1.더하다:

    더하다:

    for i, v in enumerate(y):
        ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')
    

    결과:

    y 값 v는 x 위치와 ax.text의 문자열 값이며, 편리하게 barplot은 각 막대에 대해 1의 메트릭을 가지므로 열거 i는 y 위치입니다.

  2. ==============================

    2.api 예제 코드에 각 막대에 표시된 막대의 값이있는 barchart의 예제가 있음을 알았습니다.

    api 예제 코드에 각 막대에 표시된 막대의 값이있는 barchart의 예제가 있음을 알았습니다.

    """
    ========
    Barchart
    ========
    
    A bar plot with errorbars and height labels on individual bars
    """
    import numpy as np
    import matplotlib.pyplot as plt
    
    N = 5
    men_means = (20, 35, 30, 35, 27)
    men_std = (2, 3, 4, 1, 2)
    
    ind = np.arange(N)  # the x locations for the groups
    width = 0.35       # the width of the bars
    
    fig, ax = plt.subplots()
    rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std)
    
    women_means = (25, 32, 34, 20, 25)
    women_std = (3, 5, 2, 3, 3)
    rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std)
    
    # add some text for labels, title and axes ticks
    ax.set_ylabel('Scores')
    ax.set_title('Scores by group and gender')
    ax.set_xticks(ind + width / 2)
    ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
    
    ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))
    
    
    def autolabel(rects):
        """
        Attach a text label above each bar displaying its height
        """
        for rect in rects:
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                    '%d' % int(height),
                    ha='center', va='bottom')
    
    autolabel(rects1)
    autolabel(rects2)
    
    plt.show()
    

    산출:

    참고 matplotlib의 "barh"에서 height 변수의 단위는 무엇입니까? (현재로서는 각 막대의 고정 된 높이를 설정하는 쉬운 방법이 없습니다)

  3. ==============================

    3.나는 그것이 오래된 끈이라는 것을 알고 있지만, Google을 통해 여러 번 이곳에 왔으며 아무런 대답도 아직 만족스럽지 않다고 생각합니다. 다음 기능 중 하나를 사용해보십시오 :

    나는 그것이 오래된 끈이라는 것을 알고 있지만, Google을 통해 여러 번 이곳에 왔으며 아무런 대답도 아직 만족스럽지 않다고 생각합니다. 다음 기능 중 하나를 사용해보십시오 :

    def label_bar(ax, bars, text_format, is_inside=True, **kwargs):
        """
        Attach a text label to each bar displaying its y value
        """
        max_y_value = max(bar.get_height() for bar in bars)
        if is_inside:
            distance = max_y_value * 0.05
        else:
            distance = max_y_value * 0.01
    
        for bar in bars:
            text = text_format.format(bar.get_height())
            text_x = bar.get_x() + bar.get_width() / 2
            if is_inside:
                text_y = bar.get_height() - distance
            else:
                text_y = bar.get_height() + distance
    
            ax.text(text_x, text_y, text, ha='center', va='bottom', **kwargs)
    
    
    def label_barh(ax, bars, text_format, is_inside=True, **kwargs):
        """
        Attach a text label to each horizontal bar displaying its y value
        """
        max_y_value = max(bar.get_height() for bar in bars)
        if is_inside:
            distance = max_y_value * 0.05
        else:
            distance = max_y_value * 0.01
    
    
        for bar in bars:
            text = text_format.format(bar.get_width())
            if is_inside:
                text_x = bar.get_width() - distance
            else:
                text_x = bar.get_width() + distance
            text_y = bar.get_y() + bar.get_height() / 2
    
            ax.text(text_x, text_y, text, va='center', **kwargs)
    

    이제 일반 바 플롯에 사용할 수 있습니다.

    bars = ax.bar(x_pos, values, width=0.5, align="center")
    value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
    label_bar(ax, bars, value_format, is_inside=True, color="white")
    

    수평 바 플롯의 경우 :

    horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
    value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
    label_barh(ax, horizontal_bars, value_format, is_inside=False, fontweight="bold")
    
  4. from https://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh by cc-by-sa and MIT license