Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

막대 플롯(Python Matplotlib)에서 막대 위에 텍스트를 작성하는 방법은 무엇입니까?

<시간/>

막대 그림의 막대 위에 텍스트를 쓰려면 다음 단계를 수행할 수 있습니다.

  • 그림 크기를 설정하고 서브플롯 사이 및 주변 여백을 조정합니다.
  • 연도 목록 만들기 , 인구x . 너비 변수를 초기화합니다.
  • subplots() 메소드를 사용하여 그림과 서브플롯 세트를 생성합니다.
  • ylabel 설정 , 제목 , xtickasxticklabels .
  • bar()를 사용하여 막대를 플로팅합니다. x 메서드 , 인구 및 너비 데이터.
  • 막대 패치를 반복하고 text()를 사용하여 막대 상단에 텍스트 배치 방법.
  • 그림을 표시하려면 show()를 사용하세요. 방법.

from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09,
439.23, 548.16, 683.33, 846.42, 1028.74]
x = np.arange(len(years)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
ax.set_ylabel('Population(in million)')
ax.set_title('Years')
ax.set_xticks(x)
ax.set_xticklabels(years)
pps = ax.bar(x - width / 2, population, width, label='population')
for p in pps:
height = p.get_height()
ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10,
s="{}".format(height),
ha='center')
plt.show()

출력

막대 플롯(Python Matplotlib)에서 막대 위에 텍스트를 작성하는 방법은 무엇입니까?