프로그래밍/Python

Matplotlib Bar&Histogram

Gooding 2021. 10. 6. 20:06
728x90
반응형

Bar plot

# bar
x = np.arange(10)
fig, ax = plt.subplots(figsize=(12, 4)) # 가로 12, 세로 4
ax.bar(x, x*2) # Y는 X의 2배로 설정
# x*2 = 2배 / x**2 = x^2 = x²

Bar plot은 누적 그래프 그리는 것도 가능함

x = np.random.rand(3)
y = np.random.rand(3)
z = np.random.rand(3)
data = [x, y, z]
fig, ax = plt.subplots()
x_ax = np.arange(3)
for i in x_ax:
  ax.bar(x_ax, data[i], # 데이터를 x, y, z순으로 쌓아올림
  bottom=np.sum(data[:i], axis=0)) # data를 i까지 세로로(axis=0) 쌓아올림(밑바닥 설정)
ax.set_xticks(x_ax)
ax.set_xticklabels(["A", "B", "C"]) # 라벨의 default는 0부터 시작


Histogram(도수분포표)

fig, ax = plt.subplots()
data = np.random.randn(1000)
ax.hist(data, bins=50) # bins는 막대. 1000개의 랜덤한 데이터를 50개의 막대로 나타냄


예제 👇

from elice_utils import EliceUtils
elice_utils = EliceUtils()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fname='./NanumBarunGothic.ttf'
font = fm.FontProperties(fname = fname).get_name()
plt.rcParams["font.family"] = font

# Data set
x = np.array(["축구", "야구", "농구", "배드민턴", "탁구"])
y = np.array([13, 10, 17, 8, 7])
z = np.random.randn(1000)

fig, axes = plt.subplots(1, 2, figsize=(8, 4))

# Bar 그래프
axes[0].bar(x, y)
# 히스토그램
axes[1].hist(z, bins = 200)


# elice에서 그래프 확인하기 => 내가 공부한 사이트
fig.savefig("plot.png")
elice_utils.send_image("plot.png")

반응형

'프로그래밍 > Python' 카테고리의 다른 글

Matplotlib with pandas  (0) 2021.10.07
Matplotlib 그래프  (0) 2021.10.05
Pandas groupby (2)  (0) 2021.10.01
Pandas groupby (1)  (0) 2021.09.30
Pandas 집계함수  (0) 2021.09.29