프로그래밍/Python
[Python] matplotlib.pyplot, seaborn 기본연습
비전공개미
2022. 12. 1. 19:55
반응형
SMALL
# pdplot.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(0) #seed값을 기준으로 랜덤값이 만들어진다(숫자에 큰 의미는 없음)
df = pd.DataFrame(np.random.randn(100, 3),
index=pd.date_range("12/1/2022", periods=100), #date_range("월/일/년도")
columns=["A", "B", "C"]).cumsum()
# print(df.tail())
# df.plot()
# plt.xlabel("Time")
# plt.ylabel("Value")
# plt.title("Income")
import seaborn as sns
iris = sns.load_dataset("iris")
# print(iris)
titanic = sns.load_dataset("titanic")
# print(titanic)
# print(type(iris))
# iris.sepal_length[:20].plot(kind="bar", rot=45)
# iris.sepal_length[:20].plot.bar(rot=45)
# plt.ylim(0, 10)
df = iris.groupby(iris.species).mean()
# print(df)
# df.plot.bar(rot=0)
# df.T.plot.bar(rot=0)
# pieChart
# df = titanic.pclass.value_counts()
# # print(df)
# df.plot.pie(autopct="%.2f%%")
# iris.plot.hist()
# iris.petal_length.plot.hist()
# iris.plot.kde()
# iris.plot.box()
# iris.boxplot(by="species")
# plt.tight_layout()
# plt.show() #show()를 불러줘야 출력한다
# Matplotlib
# plot
# plt.plot([1, 2, 3, 4])
# plt.plot([1, 2, 3, 4], [2, 4, 7, 12])
# plt.plot([1, 2, 3, 4], [2, 4, 7, 12], "ro-")
# t = np.arange(0, 5, 0.2)
# plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
# plt.plot(t, t, 'r--')
# plt.plot(t, t**2, 'bs')
# plt.plot(t, t**3, 'g^')
# data_dict = {"x_data":[1, 2, 3, 4, 5], "y_data":[2, 6, 8, 10, 14]}
# plt.plot("x_data", "y_data", data=data_dict)
# plt.xlabel("x_data")
# plt.ylabel("y_data")
# plt.xlabel("x_data", labelpad=15)
# plt.ylabel("y_data", labelpad=20)
# font1 = {
# "family" : "serif",
# "color" : "b",
# "weight" : "bold",
# "size" : 14
# }
# font2 = {
# "family" : "fantasy",
# "color" : "deeppink",
# "weight" : "normal",
# "size" : "xx-large"
# }
# plt.xlabel("x_data", fontdict=font1, loc="left")
# plt.ylabel("y_data", fontdict=font2, loc="bottom")
# plt.plot([1, 2, 3, 4, 5], [2, 3, 5, 7, 9], label="Price")
# plt.plot([1, 2, 3, 4, 5], [3, 6, 8, 10, 14], label="Count")
# plt.legend(loc="best")
# plt.legend(ncol=2)
# plt.legend(fontsize=14)
# plt.legend(shadow=True)
# plt.legend(frameon=False)
# plt.xlim([0, 15])
# plt.ylim([0, 15])
# plt.axis([0, 15, 0, 20])
# plt.axis("square")
# plt.axis("scaled")
# plt.axis("tight")
# plt.axis("auto")
# plt.plot([1, 2, 3], [4, 4, 4], linestyle="-", label="solid")
# plt.plot([1, 2, 3], [3, 3, 3], linestyle="--", label="dashed")
# plt.plot([1, 2, 3], [2, 2, 2], linestyle=":", label="dotted")
# plt.plot([1, 2, 3], [1, 1, 1], linestyle="-.", label="dashdot")
# plt.plot([1, 2, 3], [4, 4, 4], linestyle="solid", label="solid")
# plt.plot([1, 2, 3], [3, 3, 3], linestyle="dashed", label="dashed")
# plt.plot([1, 2, 3], [2, 2, 2], linestyle="dotted", label="dotted")
# plt.plot([1, 2, 3], [1, 1, 1], linestyle="dashdot", label="dashdot")
# plt.plot([1, 2, 3], [4, 4, 4], linestyle=(0, (1,1)), label="solid")
# plt.plot([1, 2, 3], [3, 3, 3], linestyle=(0, (1,5)), label="dashed")
# plt.plot([1, 2, 3], [2, 2, 2], linestyle=(0, (5,1)), label="dotted")
# plt.plot([1, 2, 3], [1, 1, 1], linestyle=(0, (3,5,1,5)), label="dashdot")
# plt.plot([1, 2, 3], [4, 4, 4], linestyle="-", label="solid", linewidth=10, solid_capstyle="butt")
# plt.plot([1, 2, 3], [3, 3, 3], linestyle="--", label="dashed", linewidth=10, solid_capstyle="round")
# plt.plot([1, 2, 3], [2, 2, 2], linestyle=":", label="dotted", linewidth=10, solid_capstyle="butt")
# plt.plot([1, 2, 3], [1, 1, 1], linestyle="-.", label="dashdot", linewidth=10, solid_capstyle="round")
# plt.plot([1, 2, 3], [4, 4, 4], linestyle="-", label="solid", marker="H", color="limegreen")
# plt.plot([1, 2, 3], [3, 3, 3], linestyle="--", label="dashed", marker="d", color="gold")
# plt.plot([1, 2, 3], [2, 2, 2], linestyle=":", label="dotted", marker="x", color="dodgerblue")
# plt.plot([1, 2, 3], [1, 1, 1], linestyle="-.", label="dashdot", marker="$z$", color="#CC723D")
# plt.plot([1, 2, 3], [4, 4, 4], "b-o", label="solid")
# plt.plot([1, 2, 3], [3, 3, 3], "rd--", label="dashed")
# plt.plot([1, 2, 3], [2, 2, 2], "g^:", label="dotted")
# plt.plot([1, 2, 3], [1, 1, 1], "k-.", label="dashdot")
# x = [1, 2, 3, 4, 5]
# y = [2, 3, 6, 8, 10]
# plt.plot(x, y)
# # plt.fill_between(x[1:3], y[1:3], alpha=0.5)
# # plt.fill_betweenx(y[2:4], x[2:4], alpha=0.5) #alpha(투명도)
# y1 = [3, 7, 9, 11, 15]
# plt.plot(x, y1)
# plt.fill_between(x[1:3], y[1:3], y1[1:3], color="lightgray", alpha=0.5)
# x = np.linspace(-10, 10, 100) #a, b까지 c개로 나누어라
# y = x**3
# plt.plot(x, y)
# plt.xscale("symlog")
# plt.xscale("log")
# plt.yscale("linear")
# plt.grid(True)
# plt.grid(True, axis="y", color="red", alpha=0.5, linestyle="--")
# x = np.arange(0, 2, 0.2)
# plt.plot(x, x**2, "bo-")
# plt.plot(x, x, "r*")
#
# # plt.xticks([0, 1, 2, 3, 4])
# # plt.yticks(np.arange(0, 5))
#
# plt.xticks(np.arange(0, 2, 0.5), labels=["Jan", "Feb", "Mar", "Apr"])
# plt.yticks(np.arange(0, 5), labels=["0GB", "1GB", "2GB", "3GB", "4GB"])
# plt.tick_params(axis="x", direction="in", length=10, pad=10, labelsize=12, labelcolor="b", width=3, color="b")
# plt.tick_params(axis="y", direction="inout", length=10, pad=20, labelsize=12, labelcolor="r", width=3, color="r")
#
# plt.axhline(2, 0.1, 0.9, linestyle="-", linewidth=2, color="magenta") #a = 수치 / b, c = 비율
# plt.vlines(0.5, 1, 3, linestyle="-", linewidth=2, color="cyan") #vlines(추후사용하니 기억하기)
#
# plt.legend(loc=(0.5, 0.4))
# plt.show()
# 2022/11/25
# x = np.arange(3)
# years = ["2020", "2021", "2022"]
# values = [100, 400, 900]
# colors = ["y", "b", "g"]
# plt.bar(x, values, color=colors, width=1.0)
# plt.bar(x, values, color="g")
# plt.xticks(x, years)
# plt.bar(x, values, color=colors, align="edge", edgecolor="gray", linewidth=5, tick_label=years) #align=edge 그래프를 선에맞춤
# plt.barh(x, values, color=colors, align="edge", edgecolor="gray", linewidth=5, tick_label=years)
np.random.seed(0)
# n = 100
# x = np.random.rand(n)
# y = np.random.rand(n)
#
# area = (30 * np.random.rand(n)) ** 2
# colors = np.random.rand(n)
# plt.scatter(x, y, s = area, c=colors, alpha=0.5) #alpha - 투명도
# plt.plot([1], [1], 'o', markersize=20, c='k', alpha=0.5)
# plt.colorbar()
#
# plt.text(1, 1.05, 'Plot', fontdict={"size":14})
# plt.text(0.5, 0.9, "Scatter", fontdict={"size":14}) #x좌표, y좌표, "이름", fontsize
# from mpl_toolkits.mplot3d import Axes3D
# n = 100
# xmin, xmax, ymin, ymax, zmin, zmax = 0, 20, 0, 20, 0, 50
# cmin, cmax = 0, 2
#
# xs = np.array([(xmax-xmin) * np.random.random_sample() + xmin for i in range(n)])
# ys = np.array([(ymax-ymin) * np.random.random_sample() + ymin for i in range(n)])
# zs = np.array([(zmax-zmin) * np.random.random_sample() + zmin for i in range(n)])
# color = np.array([(cmax-cmin) * np.random.random_sample() + cmin for i in range(n)])
#
# fig = plt.figure(figsize=(6, 6)) #figsize = 인치값
# ax = fig.add_subplot(111, projection="3d") #111 = 1행1열의1번째
# ax.scatter(xs, ys, zs, c=color, marker="o", s=15)
w = np.array([(150-40) * np.random.random() + 40 for _ in range(100)])
# plt.hist(w, bins=20, cumulative=True) #bins - 막대갯수, cumulative=True - 누적되는 그래프 출력
w1 = np.array([(150-40) * np.random.random() + 40 for _ in range(100)])
# plt.hist((w, w1), histtype="bar")
# plt.hist((w, w1), histtype="barstacked")
# plt.hist((w, w1), histtype="step")
# plt.hist((w, w1), histtype="stepfilled", alpha=0.5)
# w = np.array([(150-40) * np.random.random() + 40 for _ in range(10000)])
# plt.hist((w, w1), label=("w", "w1"), histtype="step", density=True) #density=True - 두그래프를 구분
# plt.legend()
ratio = [34, 32, 16, 18] #100을 기준으로 값을 맞춰야함
labels = ["Apple", "Banana", "Melon", "Grapes"]
# plt.pie(ratio, labels=labels, autopct="%.1f%%")
# plt.pie(ratio, labels=labels, autopct="%.1f%%", startangle=260, counterclock=False)
#startangle - 시작위치를 조절 / counterclock=False - 시계방향으로출력
explode = [0, 0.1, 0, 0.1]
# plt.pie(ratio, labels=labels, autopct="%.1f%%", explode=explode, shadow=True) #explode - 각항목의 간격지정
colors = ["darkgray", "gray", "lightgray", "silver"]
# plt.pie(ratio, labels=labels, autopct="%.1f%%", colors=colors)
wedgeprops = {"width":0.7, "edgecolor":"w", "linewidth":5}
# plt.pie(ratio, labels=labels, autopct="%.1f%%", colors=colors, wedgeprops=wedgeprops)
a = np.random.standard_normal((30, 40))
# cmap = plt.get_cmap("PiYG")
# cmap = plt.get_cmap("Greys")
# plt.matshow(a, cmap=cmap)
# plt.colorbar(shrink=0.8, aspect=10) #shrink - 길이 / aspect - 너비
# plt.clim(-4, 4)
from matplotlib import cm
# for cm in plt.colormaps():
# print(cm)
# a = np.random.standard_normal((8, 100))
# plt.subplot(2, 2, 1)
# # plt.scatter(a[0], a[1], c=a[1], cmap="spring")
# plt.scatter(a[0], a[1], c=a[1])
# plt.spring() #cmap 또는 각 함수로 지정해서 사용할 수 있다
# plt.subplot(2, 2, 2)
# plt.scatter(a[2], a[3], c=a[3], cmap="summer")
# plt.xticks(visible=False) #x축 없애기
# plt.yticks(visible=False) #y축 없애기
#
# plt.subplot(2, 2, 3)
# plt.scatter(a[4], a[5], c=a[5], cmap="autumn")
# plt.subplot(2, 2, 4)
# # plt.scatter(a[6], a[7], c=a[7], cmap="winter")
#
# from matplotlib.colors import LinearSegmentedColormap
# colors = ["r", "b", "y", "g"]
# cmap = LinearSegmentedColormap.from_list("my_cmap", colors, gamma=2)
# plt.scatter(a[6], a[7], c=a[7], cmap=cmap)
#
# plt.yticks(visible=False)
# print(plt.style.available) #plt스타일 목록확인
# plt.style.use("ggplot")
# plt.style.use("classic")
# plt.style.use("Solarize_Light2")
# plt.plot([1, 2, 3, 4, 5], [4, 7, 9, 10, 14])
# x = np.linspace(1, 5, 100)
# y1 = x ** 2
# y2 = x ** 3
# plt.subplot(1, 2, 1)
# plt.plot(x, y1, "-")
# plt.title("1st Graph")
# plt.subplot(1, 2, 2)
# plt.plot(x, y2, "--")
# plt.title("2nd Graph")
#
# plt.savefig("default.png")
# plt.savefig("50dpi.png", dpi=50)
# plt.savefig("200dpi.png", dpi=200)
# plt.savefig("150dpi.png", dpi=150, facecolor="#eeeeee", bbox_inches="tight", pad_inches=0.3)
# 객체 지향 인터페이스
# fig, ax = plt.subplots()
# fig = plt.figure(figsize=(8, 8))
# ax = fig.add_axes([0, 0, 1, 1])
# ax = fig.add_subplot(2, 2, 1)
# ax.set_xlabel("x")
# ax.set_ylabel("y")
# fig, ax = plt.subplots(2, 2, sharex=True, sharey=True)
# ax[0][0].set_xlabel("x")
# ax[0][0].set_ylabel("y")
# 이중 Y축
# fig, ax1 = plt.subplots()
# ax2 = ax1.twinx()
#
# x = np.arange(10)
# y1 = x + 1
# y2 = -x - 1
# ax1.plot(x, y1, color="g", label="Y1")
# ax1.legend(loc="upper left")
# ax2.plot(x, y2, color="b", label="Y2")
# ax2.legend(loc="upper right")
# x = np.arange(2020, 2030)
# y1 = np.array([10, 4, 6, 7, 15, 20, 25, 30, 15, 18])
# y2 = np.array([20, 25, 18, 18, 4, 7, 22, 21, 30, 8])
# fig, ax1 = plt.subplots()
# ax1.plot(x, y1, "o-", label="price", alpha=0.5)
# ax1.legend()
#
# ax2 = ax1.twinx()
# ax2.bar(x, y2, label="count", alpha=0.5, color="r")
# ax2.legend()
# ax1.set_zorder(ax2.get_zorder() + 10) #zorder - 차트의 앞뒤 순서를 결정
# ax1.patch.set_visible(False)
# from matplotlib import font_manager, rc
# for font in font_manager.fontManager.ttflist:
# print(font)
# font_name = font_manager.FontProperties(fname="C:\\Windows\\Fonts\\HMFMMUEX.TTC").get_name()
# rc("font", family=font_name)
# ax1.set_xlabel("연도", fontproperties=font_name)
# ax1.set_ylabel("수량", fontproperties=font_name)
# ax2.set_ylabel("재고", fontproperties=font_name)
a = np.random.normal(0, 2.0, 1000) #맨앞이 평균값
b = np.random.normal(-3, 1.5, 500)
c = np.random.normal(1.5, 1.5, 1500)
fig, ax = plt.subplots()
ax.boxplot([a, b, c], notch=True, whis=2.5, vert=False) #whis - 범위를 지정 / vert=False - 가로로
plt.tight_layout()
plt.show()
반응형
LIST