簡(jiǎn)介
matplotlib是Python的一款2D繪圖軟件,用它可以較方便的繪制出各種統(tǒng)計(jì)圖。
下面是matplotlib繪制各種圖形的基本用法,更詳細(xì)的使用方法可以參考官方文檔https://matplotlib.org/api/pyplot_summary.html
全局設(shè)置:
import numpy as np
from matplotlib import pyplot as plt#導(dǎo)入pyplot繪圖工具
%matplotlib inline#在Jupyter notebook中由于每個(gè)人的環(huán)境有差異,有些必須執(zhí)行plt.show()才能將圖片顯示出來,加上這行就不用show()也能顯示了
plt.rcParams['font.sans-serif']=["SimHei"]#
plt.rcParams['axes.unicode_minus'] = False#解決中文亂碼的問題
條形圖
plt.plot()是繪制折線圖的方法
#創(chuàng)建畫板
plt.figure(figsize=(8,4)) # 8inch*4inch
#繪制折線圖plt.plot()
plt.plot([1, 2, 3],[10, 14, 12], label="第一條線")
plt.plot([1, 2, 3], [5, 7, 4], label="第二條線")
#plt.show() 如果在pycharm中,必須要調(diào)用show函數(shù)顯示圖表
# plt.xlabel("x軸")
# plt.ylabel("y軸")
plt.legend()#圖例
plt.title("123")
# plt.show()
輸出圖像:
柱狀圖
plt.bar()
x = np.arange(1, 10, 2)
y = [5, 2, 7, 8, 2]
x1 = np.arange(2, 11, 2)
y1 = [8, 6, 2, 5, 6]
plt.bar(x, y, label="柱狀圖1")
plt.bar(x1, y1, label="柱狀圖2", color="r", width=1.1)
輸出:
條形圖
plt.barh()
使用方法同柱狀圖
直方圖
ages = np.random.randint(0, 100, 30)#年紀(jì)
bins = np.arange(0, 100, 10)
plt.hist(ages, bins, histtype="barstacked", rwidth=0.8)#年紀(jì)頻率直方圖, rwidth是柱子的寬度
輸出:
扇形圖
players = [10, 20, 3, 90]
plt.figure(figsize=(10, 10))
types = ["wow", "war3", "cs", "lol"]
plt.pie(players, #label
labels=types, #標(biāo)簽
startangle=90, #旋轉(zhuǎn)角度
shadow=True, #陰影
autopct="%1.1f%%", #百分比顯示
explode=(0, 0.2, 0, 0), #突出顯示第1個(gè)
textprops={"fontsize":20})#字體屬性,這里設(shè)大小為20
輸出:
散點(diǎn)圖
x = np.arange(1, 9)
y = np.random.randint(1, 6, 8)
plt.scatter(x, y, label="x", color="k", s=25, marker="o")
輸出:
堆疊圖
plt.stackplot(days,
sleeping,eating,working,playing,
labels=["Sleeping", "Eating", "Working", "Playing"],
colors=["r", "g", "m", "y"])
正余弦
#三角函數(shù)
plt.figure(figsize=(10, 7))#取出一張10*7的白紙
ax = plt.gca()#
ax.spines["bottom"].set_position(("data", 0))
ax.spines["left"].set_position(("data", 0))
ax.spines["top"].set_color("none")
ax.spines["right"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
X = np.linspace(-np.pi, np.pi, 512, endpoint=True)#在-np.pi~np.pi之間選擇256個(gè)等差數(shù)
S, C = np.sin(X), np.cos(X)
# print(X)
# print(S, C, sep="\n")
plt.plot(X, S, "-", lw=2, aa=False, ms=50, label="sin")#設(shè)置線寬5 關(guān)閉抗鋸齒 默認(rèn)開啟
plt.plot(X, C, "-", lw=2, aa=True, label="cos")#線寬10
plt.xlim(X.min() * 1.2, X.max() * 1.2)#橫坐標(biāo)范圍
plt.ylim(S.min() * 1.2, S.max() * 1.2)#縱坐標(biāo)范圍
plt.xticks([0, X.max(), X.min()], [0, r"$\pi$", "$-\pi$"])#橫坐標(biāo)刻度
plt.yticks([S.min(), S.max()])#縱坐標(biāo)刻度
plt.legend(fontsize=20)
t = 2 / 3 * np.pi
plt.plot([t, t], [0, np.sin(t)], "--", color="b")
plt.scatter([t], [np.sin(t)], s=100)#散點(diǎn)圖
#設(shè)置標(biāo)注
plt.annotate(r"$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$",
(t, np.sin(t)),
xycoords="data", textcoords="offset pixels",
xytext=(20, 20),
arrowprops=dict(arrowstyle="->" , connectionstyle="arc3,rad=.2"),#箭頭屬性
fontsize=16,#zi字體大小
)
plt.plot([t, t], [0, np.cos(t)], "--", color="r")
plt.scatter([t], [np.cos(t)], s=100)#散點(diǎn)圖
#設(shè)置標(biāo)注
plt.annotate(r"$\cos(\frac{2\pi}{3})=-\frac{1}{2}$",
(t, np.cos(t)),
xycoords="data", textcoords="offset pixels",
xytext=(20, 0),
arrowprops=dict(arrowstyle="->" , connectionstyle="arc3,rad=.2"),#箭頭屬性
fontsize=16,#zi字體大小
)
輸出;
加載本地csv文件并可視化
x, y = np.loadtxt("./matplotlib-demo.csv", delimiter=",", usecols=(0, 1), unpack=True)
print(x, y)
plt.plot(x, y, label="折線圖")
plt.title("numpy讀取csv文件并用matplotlib可視化")
輸出:
加載網(wǎng)絡(luò)圖片
response = requests.get("https://api.douban.com/v2/book/1220562")
print(response.text)
js_str = json.loads(response.text)
tags = js_str["tags"]
x = []
y = []
for tag in tags:
x.append(tag["name"])
y.append(tag["count"])
plt.bar(x, y, label="圖書熱門標(biāo)簽")
plt.legend()
plt.xlabel("搜索標(biāo)簽")
plt.ylabel("搜索標(biāo)簽排名")
plt.title("圖書熱詞搜索排名")
輸出: