Matplotlib에서 여러 레이블이 있는 막대 차트를 그리려면 다음 단계를 수행할 수 있습니다. -
-
men_means, men_std, women_means,에 대한 데이터 세트를 만드세요. 및 women_std .
-
numpy를 사용하여 인덱스 데이터 포인트를 만듭니다.
-
너비 초기화 바.
-
서브플롯() 사용 그림과 서브플롯 세트를 생성하는 방법.
-
rect1 만들기 및 rect2 bar()를 사용하는 막대 직사각형 방법.
-
set_ylabel() 사용 set_title() , set_xticks() 및 set_xticklabels() 방법.
-
줄거리에 범례를 배치하십시오.
-
autolabel()을 사용하여 막대 차트에 여러 레이블 추가 방법.
-
그림을 표시하려면 show()를 사용하세요. 방법.
예시
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means)) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
def autolabel(rects, xpos='center'):
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0, 'right': 1, 'left': -1}
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(offset[xpos]*3, 3), # use 3 points offset
textcoords="offset points", # in both directions
ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
plt.show() 출력
