Python/데이터 시각화

Python - [시각화] Maplotlib Pyplot 모듈 활용 그래프 그리기 (plot / bar)

GinaKim 2024. 1. 5. 23:41
728x90

fig, ax = plt.subplots(nrows= m, ncols= n, figsize=(6, 3))

 

fig = 데이터가 담기는 프레임 (액자 같은 것)

ax = 데이터가 그려지는 캔버스 

 

m개의 행과 n열로 이루어지고, 규격 사이즈가 6, 3인 그래프 (괄호 부분은 생략 가능함)

 

ax.plot() : 선 그래프
ax.bar() : 막대 그래프
ax.legend(loc = '범례 위치') : 범례


선 그래프 그리기

import matplotlib.pyplot as plt 
data1 = [10, 14, 19, 20, 25]

fig, ax = plt.subplots()
ax.plot(data1)
plt.show()

 

x축이 두개 이상인 그래프

import matplotlib.pyplot as plt

dates = [
    '2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05',
    '2021-01-06', '2021-01-07', '2021-01-08', '2021-01-09', '2021-01-10'
]
min_temperature = [20.7, 17.9, 18.8, 14.6, 15.8, 15.8, 15.8, 17.4, 21.8, 20.0]
max_temperature = [34.7, 28.9, 31.8, 25.6, 28.8, 21.8, 22.8, 28.4, 30.8, 32.0]

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 3)) # figsize=(6, 10) = 규격화
ax.plot(dates, min_temperature, label = "2021")
ax.plot(dates, max_temperature, label = "2024")
ax.legend(loc = 'upper right') # 벙례
plt.show()


막대그래프 그리기

import calendar
print(calendar.month_name[1:13]) # month 불러오기

month_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
sold_list = [300, 400, 550, 900, 600, 960, 900, 910, 800, 700, 550, 450]

fig, ax = plt.subplots()
ax.bar(month_list, sold_list)
ax.set_xticks(month_list, calendar.month_name[1:13], rotation=90) # x행 월 추가 & 회전

plt.show()

 

막대그래프 데이터 값 추가

import calendar

month_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
sold_list = [300, 400, 550, 900, 600, 960, 900, 910, 800, 700, 550, 450]


fig, ax = plt.subplots()
barcharts = ax.bar(month_list, sold_list)
ax.set_xticks(month_list, calendar.month_name[1:13], rotation=90)

print(barcharts)

for rect in barcharts:
    # print(rect)
    print(type(rect)) 
    height = rect.get_height() # y축 높이
    ax.text(rect.get_x() + rect.get_width()/2., 1.002*height,'%d' % int(height), ha='center', va='bottom')
    #print(height) 
    
plt.show()

728x90