본문 바로가기
pandas

matplotlib

by 자동매매 2023. 12. 14.

참조 :

한 권으로 끝내는 <판다스 노트>

https://e-koreatech.step.or.kr/

 

 

 

HTML color name

colors_picker

 

기본설정

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings('ignore')

 

# Unicode warning 제거 (폰트 관련 경고메시지)
plt.rcParams['axes.unicode_minus']=False

# 한글 폰트 설정
plt.rcParams['font.family'] = "Malgun Gothic"

# 그래프 출력 사이즈 설정
plt.rcParams["figure.figsize"] = (10, 8)

 

 

# 설정파일 위치 확인

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

print("설치 위치:", mpl.__file__)
print("설정 위치:", mpl.get_configdir())
print("cash 위치:", mpl.get_cachedir())
print("설정파일 위치:", mpl.matplotlib_fname())  # matplotlibrc 파일 위치

 

# font 리스트 확인

f = [f.name for f in fm.fontManager.ttflist]
f.sort()
print(f)

 

단일 그래프 생성

Copy# data 생성
data = np.arange(1, 100)
# plot
plt.plot(data)
# 그래프를 보여주는 코드
plt.show()

 

다중 그래프 (multiple graphs)

1개의 canvas 안에 다중 그래프 그리기

data = np.arange(1, 51)
plt.plot(data)

data2 = np.arange(51, 101)
# plt.figure()
plt.plot(data2)

plt.show()

 

여러개의 plot을 그리는 방법(subplot)

subplot(row, column, index)

data = np.arange(100, 201)
plt.subplot(2, 1, 1)
plt.plot(data)

data2 = np.arange(200, 301)
plt.subplot(2, 1, 2)
plt.plot(data2)

plt.show()

 

여러개의 plot을 그리는 방법(subplots) - s가 더 붙습니다.

plt.subplots(행의 갯수, 열의 갯수)

data = np.arange(1, 51)
# data 생성

# 밑 그림
fig, axes = plt.subplots(2, 3)

axes[0, 0].plot(data)
axes[0, 1].plot(data * data)
axes[0, 2].plot(data ** 3)
axes[1, 0].plot(data % 10)
axes[1, 1].plot(-data)
axes[1, 2].plot(data // 20)

plt.tight_layout()
plt.show()

 

비교  plot 그리는 방법

x_label = ["Math", "Programming", "Data Science", "Art", "English", "Physics"]
x = np.arange(len(x_label))
y_1 = [66, 80, 60, 50, 80, 10]
y_2 = [55, 90, 40, 60, 70, 20]


# subplots 생성
fig, axes = plt.subplots()

# 넓이 지정
width = 0.35


# 넓이 설정
axes.bar(x - width / 2, y_1, width, align="center", alpha=0.5)
axes.bar(x + width / 2, y_2, width, align="center", alpha=0.8)


# xtick 설정
plt.xticks(x)
axes.set_xticklabels(x_label)
plt.ylabel("Number of Students")
plt.title("Subjects")

plt.legend(["john", "peter"])

plt.show()

 

 

 

 

 

설정

 

from IPython.display import Image

# 출처: matplotlib.org
Image('https://matplotlib.org/_images/anatomy.png')

 

 

 

일보정리.xlsx
1.49MB

 

df = pd.read_excel("일보정리.xlsx", index_col=0)

cond = df[0] == "합계"
df1 = df.loc[cond, 17]


plt.plot(df1)

# 타이틀 & font 설정
plt.title("유입유량 Graph", fontsize=20)

# X축 & Y축 Label 설정
plt.xlabel("일자", fontsize=15)
plt.ylabel("㎥/day", fontsize=15)

# X tick, Y tick 설정
plt.xticks(rotation=60)
plt.yticks()

# legend 설정
plt.legend(["유입유량"], fontsize=15)

# x, y limit 설정
import datetime

start_date = datetime.date(2023, 1, 1)
last_date = datetime.date(2023, 7, 31)
plt.xlim(start_date, last_date)
plt.ylim(8000, 25000)

plt.show()

 

 

세부 도큐먼트 확인하기

marker의 종류

'.' point marker '^' triangle_up marker '2' tri_up marker 'p' pentagon marker '+' plus marker '|' vline marker
',' pixel marker '<' triangle_left marker '3' tri_left marker '*' star marker 'x' x marker '_' hline marker
'o' circle marker '>' triangle_right marker '4' tri_right marker 'h' hexagon1 marker 'D' diamond marker  
'v' triangle_down marker '1' tri_down marker 's ' square marker 'H' hexagon2 marker 'd' thin_diamond marker  

 

# marker, markersize 설정
plt.plot(df1, marker="o", markersize=3)

plt.show()

 

 

line의 종류

'-' solid line style '--' dashed line style '-.' dash-dot line style ':' dotted line style

 

# linestyle 설정
plt.plot(df1, marker="o", markersize=3, linestyle=':')

 

 

color의 종류

'b' blue 'r' red 'm' magenta 'k' black
'g' green 'c' cyan 'y' yellow 'w' white

 

# color 설정
plt.plot(df1, marker="o", markersize=3, linestyle=":", color="c")

 

투명도 설정 : 0 ~1

# 투명도 설정
plt.plot(df1, marker="o", markersize=3, linestyle=":", color="m", alpha=0.5)

 

 

grid 설정

# grid 옵션 추가
plt.grid()

 

 

annotate 설정

# annotate 설정
plt.annotate(
    "최대 유량",
    xy=(datetime.date(2023, 6, 29), 24300),
    xytext=(datetime.date(2023, 7, 10), 23000),
    arrowprops=dict(facecolor="blue", shrink=0.05),
)

 

'pandas' 카테고리의 다른 글

pd / 날짜 / 시간  (0) 2023.12.16
matplotlib 그래프 종류  (0) 2023.12.15
연결(Concat)과 병합(Merge)  (0) 2023.12.12
Groupby와 Pivot table  (0) 2023.12.12
데이터 전처리, 추가, 삭제, 변환  (0) 2023.12.12

댓글