본문 바로가기
pandas

matplotlib 그래프 종류

by 자동매매 2023. 12. 15.

참조 :

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

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

 

from IPython.display import Image
import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings('ignore')

plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.family'] = 'Malgun Gothic'
plt.rcParams['figure.figsize']=(10,8)

 

Scatterplot

x = np.random.rand(50)
y = np.random.rand(50)
colors = np.arange(50)
area = x * y * 250

plt.scatter(x, y, s=area, c=colors)
plt.show()

 

 

plt.figure(figsize=(12,6))

plt.subplot(131)
plt.scatter(x, y, s=area, color="purple", alpha=0.1)
plt.title("alpha=0.1")

plt.subplot(132)
plt.title("alpha=0.5")
plt.scatter(x, y, s=area, color="purple", alpha=0.5)

plt.subplot(133)
plt.title("alpha=1.0")
plt.scatter(x, y, s=area, color="purple", alpha=1.0)

plt.show()

 

 

 

Barplot 생성

x = ["Math", "Programming", "Data Science", "Art", "English", "Physics"]
y = [66, 80, 60, 50, 80, 10]

plt.figure(figsize=(6, 3))

plt.subplot(121)
# plt.bar(x, y)
plt.bar(x, y, align="center", alpha=0.7, color="red")
plt.title("Subjects")
plt.ylabel("Number of Students")
plt.xticks(x)
plt.xticks(rotation=60)


plt.subplot(122)
plt.barh(x, y, align="center", alpha=0.7, color="green")
plt.yticks(x)
plt.xlabel("Number of Students")
plt.title("Subjects")
plt.tight_layout()

plt.show()

 

 

 

Batplot에서 비교 그래프 그리기

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()

 

 

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]

# 넓이 지정
width = 0.35

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

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

# xtick 설정
plt.yticks(x)
axes.set_yticklabels(x_label)
plt.xlabel("Number of Students")
plt.title("Subjects")

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

plt.show()

 

 

 

Line Plot

x = np.arange(0, 10, 0.1)
y_1 = 1 + np.sin(x)
y_2 = 1 + np.cos(x)

plt.plot(x, y_1, label="1+sin", color="blue", alpha=0.3)
plt.plot(x, y_2, label="1+cos", color="red", alpha=0.7)

plt.xlabel("x value", fontsize=15)
plt.ylabel("y value", fontsize=15)
plt.title("sin and cos graph", fontsize=18)

plt.grid()
plt.legend()

plt.show()

 

Areaplot(Filled Area)

x = np.arange(1, 10, 0.05)
y_1 = np.cos(x) + 1
y_2 = np.sin(x) + 1
y_3 = y_1 * y_2 / np.pi

plt.fill_between(x, y_1, color="green", alpha=0.1)
plt.fill_between(x, y_2, color="blue", alpha=0.2)
plt.fill_between(x, y_3, color="red", alpha=0.3)
plt.plot(x, y_3, color="red", alpha=0.8)

 

 

Histogram

N = 100000
bins = 30

x = np.random.randn(N)

# sharey: y축을 다중 그래프가 공유
# tight_layout: graph의 패딩을 자동으로 조절해주어 fit한 graph를 생성
fig, axs = plt.subplots(1, 3, sharey=True, tight_layout=True)

fig.set_size_inches(12, 5)

axs[0].hist(x, bins=bins)
axs[1].hist(x, bins=bins * 2)
axs[2].hist(x, bins=bins * 4)

 

 

N = 100000
bins = 30

x = np.random.randn(N)

fig, axs = plt.subplots(1, 2, tight_layout=True)
fig.set_size_inches(9, 3)

# density=True 값을 통하여 Y축에 density를 표기할 수 있습니다.
axs[0].hist(x, bins=bins, density=True, cumulative=True)
axs[1].hist(x, bins=bins, density=True)

plt.show()

 

 

Pie Chart

labels = ["Samsung", "Huawei", "Apple", "Xiaomi", "Oppo", "Etc"]
sizes = [20.4, 15.8, 10.5, 9, 7.6, 36.7]
explode = (0.3, 0, 0, 0, 0, 0)

# texts, autotexts 인자를 활용하여 텍스트 스타일링을 적용합니다
# texts는 label에 대한 텍스트 효과
# autotexts는 파이 위에 그려지는 텍스트 효과
patches, texts, autotexts = plt.pie(
    sizes,
    explode=explode,  # 파이에서 툭 튀어져 나온 비율
    labels=labels,
    autopct="%1.1f%%",  # 퍼센트 자동으로 표기
    shadow=True,  # 그림자 표시
    startangle=90,  # 파이를 그리기 시작할 각도
)

plt.title("Smartphone pie", fontsize=15)

# label 텍스트에 대한 스타일 적용
for t in texts:
    t.set_fontsize(12)
    t.set_color("gray")

# pie 위의 텍스트에 대한 스타일 적용
for t in autotexts:
    t.set_color("white")
    t.set_fontsize(18)

plt.show()

 

 

Box Plot

# 샘플 데이터 생성
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))


plt.tight_layout()
plt.subplot(1, 3, 1)
plt.title("기본 Plot", fontsize=15)
plt.boxplot(data)

# Box Plot 축 바꾸기 : vert=False 옵션
plt.subplot(1, 3, 2)
plt.title("Horizontal Box Plot", fontsize=15)
plt.boxplot(data, vert=False)

plt.subplot(1, 3, 3)
plt.title("Changed Outlier Symbols", fontsize=15)
outlier_marker = dict(markerfacecolor="r", marker="D")
plt.boxplot(data, flierprops=outlier_marker)


plt.show()

 

 

3D 그래프

from mpl_toolkits import mplot3d

# 밑그림 그리기 (캔버스)
fig = plt.figure()
ax = plt.axes(projection="3d")  # project=3d로 설정

# x, y, z 데이터를 생성
z = np.linspace(0, 15, 1000)
x = np.sin(z)
y = np.cos(z)

ax.plot3D(x, y, z, "gray")
plt.show()

 

'pandas' 카테고리의 다른 글

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

댓글