繪圖神器-matplotlib入門

此次,讓咱們使用一個很是有名且十分有趣的玩意兒來完成今天的任務,它就是jupyter。html

1、安裝jupyter

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

啓動jupyter也十分簡單:jupyter notebookpython

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

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

新文件長這樣。雖然說每一個cell獨立,可是下一個cell仍是能夠引用上一個cell的變量api

補充: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瀏覽器

 

2、matplotlib入門

什麼是matplotlibruby

官方給出的解釋是: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.markdown

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

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

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

(matplotlib、numpy,這倆貨是機器學習三劍客中的兩個)

牛刀小試:

# 代碼雖然只有3行,但卻很是直觀的繪製出了一條線形圖

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

# plt.plot(data):將上述數組繪製出來,對應圖中y軸,而matplotlib自己默認根據data數組中的數量給咱們設置了[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軸的值

# 第三個參數則代表線形圖是屬性,圖的構成和顏色,如上一依次是:紅色直線、綠色點線、黃色直線

 

# 更多plot繪製線形圖的內容,請參考:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot

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

 

相關文章
相關標籤/搜索