본문 바로가기
Python

[Python] matplotlib.pyplot 을 이용해서 bar(막대) chart 만들기

by bryan.oh 2022. 2. 16.
반응형

matplotlib.pyplot
bar chart

요런거 간단하게 만들어 보겠습니다.

라이브러리 설치

pip install matplotlib
또는 requirements.txt 에
matplotlib==3.5.1

최신 release 확인하기

 

import

import numpy as np
import matplotlib.pyplot as plt

 

데이터 만들기

height = [85, 95, 91, 78]
bars = ('hello','bryan','tom','cat')
y_pos = np.arange(len(bars))

height(y축) 는 시험성적이고,  x 축은 학생이름으로 보겠습니다.

 

bar 생성

plt.bar(y_pos, height)

 

X축 이름 생성

plt.xticks(y_pos, bars)

 

pycharm 에서 실행하여 이미지 확인

plt.show()

pycharm 우측에 Plots 영역에 이미지가 표시됩니다.

 

이미지로 저장하기

plt.savefig('test.png')

파라메터로 받은 path 에 이미지를 생성합니다. (지금 코드와 같은 경로에 test.png 라는 파일이 생성됩니다)

 

전체 코드

import numpy as np
import matplotlib.pyplot as plt

height = [85, 95, 91, 78]
bars = ('hello','bryan','tom','cat')
y_pos = np.arange(len(bars))

plt.bar(y_pos, height)

plt.xticks(y_pos, bars)

plt.show()

plt.savefig('test.png')

 

옵션

- bar 의 색상 변경

plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
# color 는 RGBA

- bar 의 border 색상 설정

plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6), edgecolor='blue')

- bar 마다 다른 색상 설정

plt.bar(y_pos, height, color=['red', 'green', 'blue', 'yellow'])

rgb 코드 배열도 가능합니다.

['#c1abff', '#d8e1c5', '#80afe5', '#ddadd0', '#ebbfea', '#84cec0', '#9acee9', '#d6c2b6', '#d48c9d', '#dcf6c5']

 

랜덤으로 RGB 색상 생성하기

import random
def get_random_color(color_count, is_rgba=False):
    number_hex = 8 if is_rgba else 6
    return ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(number_hex)])
             for i in range(color_count)]

 

 

참고

savefig 파라메터들

728x90
반응형

댓글