matplotlib繪制各類圖形

簡(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("圖書熱詞搜索排名")

輸出:
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Matplotlib 入門教程 來源:Introduction to Matplotlib and basic l...
    布客飛龍閱讀 32,241評(píng)論 5 162
  • 一、概述 深度學(xué)習(xí)的一個(gè)重要手段是訓(xùn)練數(shù)據(jù)和訓(xùn)練過程的可視化,因此,我們關(guān)于深度學(xué)習(xí)的系列介紹文章就從Matplo...
    aoqingy閱讀 6,558評(píng)論 0 24
  • Matplotlib 入門知識(shí) matplotlib在Python中應(yīng)用最多的2D圖像的繪圖工具包,使用matpl...
    文婷_5250閱讀 1,683評(píng)論 0 1
  • matplotlib 本文是在ipython notebook上編寫,是matplot的學(xué)習(xí)筆記 對(duì)一些常用的圖形...
    任海亮閱讀 8,719評(píng)論 2 17
  • 人生的過程,不就像一面鏡子,在擦鏡子上的灰塵時(shí),好看清自己的樣子,看清自己的路,當(dāng)明白自己正走在屬于自己的路上,就...
    寫字人已失蹤閱讀 190評(píng)論 1 1

友情鏈接更多精彩內(nèi)容