
- Matplotlib는 데이터 시각화를 위한 가장 널리 사용되는 라이브러리이다.
- 주로 2D 플롯을 생성하는데 사용된다.
# 터미널에 install
# 윈도우 설치
pip install matplotlib
#맥 설치
pip3 install matplotlib
# 굳이 선언 안해도 되지만 선언하면 손쉽게 불러와서 사용 가능
import matplotlib.pyplot as plt
# 데이터 불러오기 위해 pandas 설치 필요(pip install pandas,import pandas as pd )
# 데이터 이름 = pd.read_csv("데이터 경로/데이터 이름.csv")
ecommerce_df = pd.read_csv("../00_data/ecommerce_sales.csv"
ecommerce_df = pd.read_csv("../00_data/ecommerce_sales.csv", encoding="latin1")
# InvoiceDate 컬럼을 날짜 형식으로 변경
ecommerce_df["InvoiceDate"] = pd.to_datetime(ecommerce_df["InvoiceDate"])
ecommerce_df["TotalPrice"] = ecommerce_df["Quantity"] * ecommerce_df["UnitPrice"]
dail_sales = ecommerce_df.groupby(ecommerce_df["InvoiceDate"].dt.date)["TotalPrice"].sum()
plt.figure(figsize=(10,6))
plt.rc("font", family="Malgun Gothic")
# plot 차트를 그리는 매서드이다.
plt.plot(dail_sales.index, dail_sales.values, label="날짜별 총 판매 금액")
plt.title("날짜별 총 판매 금액 변화")
plt.xlabel("날짜")
plt.xticks(rotation=45)
plt.ylabel("총 판매 금액")
plt.legend()
plt.tight_layout()
plt.show()

막대형 그래프는 각 카테고리가 갖는 값을 막대 높이로 표현하여, 데이터를 직관적으로 비교할 수 있다.
# 축의 값 포맷을 사용자 정의 형식으로 지정하기 위해서 사용하는 도구이다.
from matplotlib.ticker import FuncFormatter
ecommerce_df = pd.read_csv("../00_data/ecommerce_sales.csv", encoding="latin1")
ecommerce_df["InvoiceDate"] = pd.to_datetime(ecommerce_df["InvoiceDate"])
filtered_df = ecommerce_df[(ecommerce_df["InvoiceDate"] > "2010-12-01")& (ecommerce_df["InvoiceDate"] < "2011-06-01")].copy()
filtered_df["Total"] = filtered_df["Quantity"] * filtered_df["UnitPrice"]
country_salse = filtered_df.groupby("Country")["Total"].sum()
plt.figure(figsize=(20,6))
# 막대 그래프를 그리는 메서드이다.
plt.bar(country_salse.index, country_salse.values, label="지역별 총 판매 금액")
plt.xlabel("지역")
plt.xticks(rotation=45)
plt.ylabel("금액")
formatter = FuncFormatter(lambda x, _: f'{int(x):,}')
plt.gca().yaxis.set_major_formatter(formatter)
plt.tight_layout()
plt.legend()
plt.show()

- 히스토그램은 데이터 분포를 시각화하는데 사용한다.
- 즉 데이터의 빈도를 막대 형태로 표현한다.
- 가로 축에는 데이터의 구간, 세로 축에는 해당 구간에 속하는 데이터의 빈도(횟수나 개수 등)를 나타낸다.
human_df = pd.read_csv("../00_data/Human_Resources.csv", encoding="latin1")
plt.figure(figsize=(20,6))
plt.hist(human_df["Age"], bins=50, color="skyblue", edgecolor="black")
plt.title("나이 분포")
plt.xlabel("나이")
plt.xticks(rotation=45)
plt.ylabel("분포")
plt.show()

산점도는 두 변수 간의 상관관계를 시각화 하는데 유용하다.
stock_df = pd.read_csv("../00_data/stock_daily_prices.csv")
goog = stock_df["GOOG"]
amzn = stock_df["AMZN"]
plt.figure(figsize=(10,5))
plt.scatter(goog, amzn)
plt.title("goog와 amzn의 상관관계")
plt.xlabel("구글 가격")
plt.ylabel("아마존 가격")
plt.show()

하나의 그래프에 여러 데이터를 겹쳐서 비교할 때 유용하다.
stock_df = pd.read_csv("../00_data/stock_daily_prices.csv")
filtered_df = stock_df[(stock_df["Date"] > "2020-07-10") & (stock_df["Date"] < "2020-08-05")].copy()
plt.figure(figsize=(10,6))
plt.plot(filtered_df["Date"], filtered_df["AAPL"], label="AAPL", color="green", marker="o")
plt.plot(filtered_df["Date"], filtered_df["AMZN"], label="AMZN", color="blue", marker="x")
plt.plot(filtered_df["Date"], filtered_df["GOOG"], label="GOOG", color="red", marker="s")
plt.plot(filtered_df["Date"], filtered_df["TSLA"], label="TSLA", color="purple", marker="^" )
plt.title("주식 가격 비교")
plt.xlabel("Date")
plt.ylabel("stock Price")
plt.xticks(rotation=45)
plt.legend()
plt.tight_layout()
plt.show()

- 하나의 figure 내에 여러 개의 그래프를 배치 가능하다.
- 여러 데이터를 한번에 비교할 때 유용하다.