1. 程式人生 > >繪圖神器-matplotlib入門

繪圖神器-matplotlib入門

dom 沒有 自動啟動 opc ros put ima 向上 rpo

這次,讓我們使用一個非常有名且十分有趣的玩意兒來完成今天的任務,沒錯它就是jupyter。

一、安裝jupyter

matplotlib入門之前,先安裝好jupyter。這裏只提供最為方便快捷的安裝方式:pip install jupyter

我這裏已經裝過了

技術分享圖片

啟動jupyter也十分簡單:jupyter notebook

技術分享圖片

執行命令後,自動啟動服務,並自動打開瀏覽器,jupyter就長這樣

技術分享圖片

找到你想要的目錄,右上角new-->python3新建一個可以執行python3代碼的jupyter文件

技術分享圖片

新文件長這樣。雖說每個cell獨立,但是下一個cell還是可以引用上一個cell的變量

技術分享圖片

補充:jupyter下一些常用的快捷命令

ctrl+enter 執行當前cell
shift+enter 執行當前cell並跳到下一個cell
dd 刪除當前cell
a 向上建一個cell
b 向下建一個cell
esc+m/m 將當前cell切換為markdown模式
esc+y/y 將當前cell切換為code模式
esc+l/l 顯示/隱藏當前cell的行號
o 收起或打開當前cell的output
shift 選中多個cell
shift+m 合並多個cell

二、matplotlib入門

什麽是matplotlib?

官方給出的解釋是:Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with just a few lines of code.

Matplotlib是一個Python的2D繪圖庫它以各種硬拷貝格式和跨平臺的交互式環境生成出版質量級別的圖形。只需要幾行代碼,你就可以生成繪圖,直方圖,功率譜,條形圖,錯誤圖,散點圖等。

0.安裝依賴庫:matplotlib、numpy(pip install *)

numpy是python的一種開源的數值計算擴展庫。這種工具可用來進行大型矩陣數據類型處理、矢量處理,以及精密運算。

(小聲說一句,這倆貨是機器學習三劍客中的兩個)

牛刀小試:

技術分享圖片

可以看到,代碼雖然只有3行,但卻非常直觀的繪制出了一條線形圖。

data = np.arange(100, 200) :生成100-200之間的整數數組,它的值是[100,101...200]

plt.plot(data):將上述數組繪制出來,對應圖中y軸,而matplotlib本身默認給我們設置了[0,100]的x軸,使其一一對應

plt.show():將圖片展示出來

1.繪制線形圖

import matplotlib.pyplot as plt

plt.plot([100, 200, 300], [300, 600, 900], -r)
plt.plot([100, 200, 300], [200, 400, 900], :g)
plt.plot([200, 300, 400], [800, 100, 600], -y)

plt.show()

技術分享圖片

plot接受的三個參數,第一個參數是數組,作為x軸的值;第二個參數也是數組,作為y軸的值;第三個參數則表明線形圖是屬性,圖的構成和顏色,如上一依次是:紅色直線、綠色點線、黃色直線。

2.繪制散點圖

import matplotlib.pyplot as plt
import numpy as np

N = 20

plt.scatter(np.random.rand(N) * 100,
           np.random.rand(N) *100,
           c=r, s=100, alpha=0.5)

plt.scatter(np.random.rand(N) * 100,
           np.random.rand(N) *100,
           c=y, s=200, alpha=0.8)

plt.scatter(np.random.rand(N) * 100,
           np.random.rand(N) *100,
           c=b, s=300, alpha=0.5)

plt.show()

技術分享圖片

這幅圖包含了三組數據,每組數據都包含了20個隨機坐標的位置。參數c表示點的顏色,s是點的大小,alpha是透明度

scatter繪制散點圖詳細文檔,參考:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html#matplotlib.pyplot.scatter

3.餅狀圖

import matplotlib.pyplot as plt
import numpy as np

labels = [suger, popo, python, java, ruby, c#]
data = np.random.rand(6) * 100

plt.pie(data, labels=labels, autopct=%1.1f%%)
plt.axis(equal)
plt.legend()

plt.show()

技術分享圖片

data是一組包含6個數據的隨機數值;圖中的標簽通過labels來指定;autopct指定了數值的精度格式;plt.axis(‘equal‘)設置了坐標軸大小一致;plt.legend()指明要繪制圖。

pie繪制餅狀圖詳細參考:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html?highlight=pie#matplotlib.pyplot.pie

4.條形圖

import matplotlib.pyplot as plt
import numpy as np

N = 7
x = np.arange(N)

data = np.random.randint(low=0, high=100, size=N)
colors = np.random.rand(N * 3).reshape(N, -1)
labels = [Mon, Tue, Wed, Thu, Fri, Sat, Sun]

plt.title(Weekday Data)
plt.bar(x, data, alpha=0.8, color=colors, tick_label=labels)
plt.show()

技術分享圖片

# 此圖展示了一組包含7個隨機數值的結果,每個數值是[0, 100]的隨機數
# 它們的顏色也是通過隨機數生成的。np.random.rand(N * 3).reshape(N, -1)表示先生成21(N x 3)個隨機數,然後將它們組裝成7行,那麽每行就是三個數,這對應了顏色的三個組成部分
# title指定了圖形的標題,labels指定了標簽,alpha是透明度

bar繪制條形圖官方文檔:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html?highlight=bar#matplotlib.pyplot.bar

5.直方圖

import matplotlib.pyplot as plt
import numpy as np

data = [np.random.randint(0, n, n) for n in [3000, 4000, 5000]]
labels = [3k, 4k, 5k]
bins = [0, 100, 500, 1000, 2000, 3000, 4000, 5000]

plt.hist(data, bins=bins, label=labels)
plt.legend()

plt.show()

技術分享圖片

# [np.random.randint(0, n, n) for n in [3000, 4000, 5000]]生成了包含3個數組的數組:第一個數組包含了3000個隨機數,這些隨機數的範圍是 [0, 3000);第二個數組包含了4000個隨機數,這些隨機數的範圍是 [0, 4000);第三個數組包含了5000個隨機數,這些隨機數的範圍是 [0, 5000)

# bins設置直方圖的邊界。[0, 100, 500, 1000, 2000, 3000, 4000, 5000]一共設置了7個邊界,如:第一個邊界是[0,100),則有一個據點,符合邊界範圍的圖片將會在其中繪制

# 三組數據都有3000以下的數據,圖中3000以下的據點也都有數據,[3000,4000)據點沒有了3k的數據,而[4000,5000)據點則只剩下5k的數據了

hist繪制直方圖的更多用法:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html?highlight=hist#matplotlib.pyplot.hist

以上,目前我們已經學會了繪制簡單的線形圖、散點圖、餅狀圖、條形圖和直方圖,顯然這只是皮毛,真正讓人嘆為觀止的圖,盡在matplotlib gallery。

這裏摘取一個示例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

w = 3
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)

fig = plt.figure(figsize=(7, 9))
gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])

#  Varying density along a streamline
ax0 = fig.add_subplot(gs[0, 0])
ax0.streamplot(X, Y, U, V, density=[0.5, 1])
ax0.set_title(Varying Density)

# Varying color along a streamline
ax1 = fig.add_subplot(gs[0, 1])
strm = ax1.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=autumn)
fig.colorbar(strm.lines)
ax1.set_title(Varying Color)

#  Varying line width along a streamline
ax2 = fig.add_subplot(gs[1, 0])
lw = 5*speed / speed.max()
ax2.streamplot(X, Y, U, V, density=0.6, color=k, linewidth=lw)
ax2.set_title(Varying Line Width)

# Controlling the starting points of the streamlines
seed_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1,  0, 1, 2, 2]])

ax3 = fig.add_subplot(gs[1, 1])
strm = ax3.streamplot(X, Y, U, V, color=U, linewidth=2,
                     cmap=autumn, start_points=seed_points.T)
fig.colorbar(strm.lines)
ax3.set_title(Controlling Starting Points)

# Displaying the starting points with blue symbols.
ax3.plot(seed_points[0], seed_points[1], bo)
ax3.axis((-w, w, -w, w))

# Create a mask
mask = np.zeros(U.shape, dtype=bool)
mask[40:60, 40:60] = True
U[:20, :20] = np.nan
U = np.ma.array(U, mask=mask)

ax4 = fig.add_subplot(gs[2:, :])
ax4.streamplot(X, Y, U, V, color=r)
ax4.set_title(Streamplot with Masking)

ax4.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5,
          interpolation=nearest, cmap=gray, aspect=auto)
ax4.set_aspect(equal)

plt.tight_layout()
plt.show()

技術分享圖片

繪圖神器-matplotlib入門