Python可視化庫(kù)(繪制圖表):matplotlib

動(dòng)機(jī)

作為一個(gè)初級(jí)JAVA工作者,最近嘗試學(xué)習(xí)機(jī)器學(xué)習(xí),看完暈頭轉(zhuǎn)向的一些概念之后,嘗試實(shí)現(xiàn)了第一個(gè)PLA感知機(jī)算法,成功之后甚至想叉腰得瑟一會(huì)。正在得意洋洋之時(shí),如何讓算法結(jié)果可視化呢,網(wǎng)上搜索了半天發(fā)現(xiàn)了一個(gè)好用的python第三方庫(kù)matplotlib。

matplotlib可以做什么

Matplotlib 能夠創(chuàng)建多數(shù)類型的圖表,如條形圖,散點(diǎn)圖,條形圖,餅圖,堆疊圖,3D 圖和地圖圖表。并且可以對(duì)圖片進(jìn)行調(diào)整并且保存。既然是可視化工具,就不過多介紹讓我們直接實(shí)戰(zhàn)體驗(yàn)吧??赡苓€會(huì)用到Python的一個(gè)第三方科學(xué)計(jì)算庫(kù)numpy,其功能主要是對(duì)向量的一些科學(xué)計(jì)算,只會(huì)用到比較簡(jiǎn)單的計(jì)算。

實(shí)戰(zhàn)演練

準(zhǔn)備工作

安裝matplotlib非常方便,Python3自帶pip直接如下安裝即可:

pip install matplotlib

安裝完成后需要引入模塊如下,我們習(xí)慣將numpy別名為np,matplotlib別名為plt,為了節(jié)省篇幅就不重復(fù)導(dǎo)入了

import matplotlib.pyplot as plt
import numpy as np

直線

首先我們構(gòu)造出想畫出的向量,然后調(diào)用plt.plot()繪制,通過plt.show()展現(xiàn)出來(lái),如果想直接保存到本地可以加上plt.savefig()方法。讓我們從畫一條線開始吧。

x = np.array([1, 2, 3])
plt.plot(x)
plt.show()
line1.png

這個(gè)庫(kù)用起來(lái)真的很簡(jiǎn)單,我們?cè)囋嚠媰蓷l線并且再添加一些說明信息

x = np.array([1, 2, 3])
y = np.array([5, 6, 7])
plt.plot(x, label='first line')
plt.plot(y, label='second line')
# 橫坐標(biāo)注釋
plt.xlabel('Plot Number')
# 列坐標(biāo)注釋
plt.ylabel('Important var')
# 生成表標(biāo)題
plt.title('Matplotlib demo\nCheck it out')
# 生成小方塊顯示每條線對(duì)應(yīng)的label
plt.legend()
plt.show()
twoline.png

條形圖

one = np.array([[1, 3, 5, 7, 9], [3, 4, 6, 12, 7]])
two = np.array([[2, 4, 6, 8, 10], [4, 2, 9, 8, 11]])
# 參數(shù)1是橫坐標(biāo),參數(shù)2是高度
plt.bar(one[0], one[1], label='first')
plt.bar(two[0], two[1], label='second')
plt.xlabel('bar-hist Number')
# 列坐標(biāo)注釋
plt.ylabel('bar-hist height')
# 生成表標(biāo)題
plt.title('Matplotlib demo\nCheck it out')
# 生成小方塊顯示每條線對(duì)應(yīng)的label
plt.legend()
plt.show()
bar1.png

直方圖

# 原始數(shù)據(jù)
population_ages = [22, 55, 62, 45, 21, 22, 34, 42, 42, 4, 99, 102, 110, 120, 121, 122, 130, 111, 115, 112, 80, 75, 65,
                   54, 44, 43, 42, 48, 12, 32, 44, 9, 7]
# 橫坐標(biāo),表示增量
bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130]
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.show()
hist1.png

散點(diǎn)圖

data = np.array([[1, 2], [2, 3], [5, 6]])
# marker有許多圖標(biāo):https://matplotlib.org/api/markers_api.html
plt.scatter(data[:, 0], data[:, 1], label='skitscat', color='k', s=25, marker="o")
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.legend()
plt.show()
scatter1.png

堆疊圖

days = [1, 2, 3, 4, 5]
sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]

plt.plot([], [], color='m', label='Sleeping', linewidth=2)
plt.plot([], [], color='c', label='Eating', linewidth=2)
plt.plot([], [], color='r', label='Working', linewidth=2)
plt.plot([], [], color='k', label='Playing', linewidth=2)

plt.stackplot(days, sleeping, eating, working, playing, colors=['m',
                                                                'c', 'r', 'k'])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.legend()
plt.show()
stacked1.png

餅圖

slices = [7, 2, 5, 11]
activities = ['sleeping', 'eating', 'working', 'playing']
cols = ['c', 'm', 'r', 'b']
# slices是切片比例,startangle是起始角度,explode可以拿出不是0的切片
plt.pie(slices,
        labels=activities,
        colors=cols,
        startangle=90,
        shadow=True,
        explode=(0, 0.1, 0, 0),
        autopct='%1.1f%%')
plt.title('Matplotlib demo\nCheck it out')
plt.show()
pie1.png

文件中加載數(shù)據(jù)

"""
test1.txt 內(nèi)容格式如下
0   0
1  1
2  12
3  11
4  15
5  18
6  9
7  5
8  2
9  16
...
"""
data = np.loadtxt('../data/test1.txt', unpack=True)
plt.plot(data[0], data[1], label='Loaded from local file')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.legend()
plt.show()
loaddata1.png

樣式

style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(212)
data = np.loadtxt('../data/test1.txt', unpack=True)
ax1.plot(data[0], data[1])
ax2.plot(data[0], data[1])
ax3.plot(data[0], data[1])
plt.xlabel('x')
plt.ylabel('y')
plt.show()
style1.png

子圖

style.use('ggplot')
# 創(chuàng)建子圖,1*1網(wǎng)格,起點(diǎn)(0,0)
fig = plt.figure()
ax1 = plt.subplot2grid((1, 1), (0, 0))
ax1.xaxis.label.set_color('c')
ax1.yaxis.label.set_color('r')
# 數(shù)軸距離
ax1.set_yticks([0, 1.5, 2.5, 3.5])
data = np.array([[1, 2], [3, 4]])
# 填充
ax1.fill_between([0, 1], 0, [0, 1])
# 改邊框
ax1.spines['left'].set_color('c')
ax1.spines['left'].set_linewidth(5)
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.tick_params(axis='x', colors='#f06215')
plt.plot(data)
plt.xlabel('Plot Number')
plt.ylabel('Important var')
plt.title('Matplotlib demo\nCheck it out')
plt.show()
![3d1.png](https://upload-images.jianshu.io/upload_images/13674655-b8ffc10cee4a21d2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

3D圖

style.use('ggplot')
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [5, 6, 7, 8, 2, 5, 6, 3, 7, 2]
z = [1, 2, 6, 3, 2, 7, 3, 3, 7, 2]
x2 = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
y2 = [-5, -6, -7, -8, -2, -5, -6, -3, -7, -2]
z2 = [1, 2, 6, 3, 2, 7, 3, 3, 7, 2]
ax1.scatter(x, y, z, c='g', marker='o')
ax1.scatter(x2, y2, z2, c='r', marker='o')
ax1.set_xlabel('x axis')
ax1.set_ylabel('y axis')
ax1.set_zlabel('z axis')
plt.show()
3d1.png
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
x = np.array([[1, 2, 3], [5, 6, 7]])
y = np.array([[5, 6, 7], [5, 2, 4]])
z = np.array([[1, 2, 6], [1, 2, 9]])
ax1.plot_wireframe(x, y, z)
ax1.set_xlabel('x axis')
ax1.set_ylabel('y axis')
ax1.set_zlabel('z axis')
plt.show()
3d2.png

動(dòng)態(tài)圖

style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

def animal1(i):
    data = np.loadtxt('../data/animal.txt', unpack=True)
    ax1.clear()
    ax1.plot(data[0], data[1])

ani = animation.FuncAnimation(fig, animal1, interval=1000)
plt.show()

動(dòng)態(tài)向文件中寫入數(shù)據(jù)可以監(jiān)控顯示數(shù)據(jù)變化

最后編輯于
?著作權(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)容

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