Matplotlib 是一個(gè) Python 的 2D繪圖庫(kù)夹界,通過(guò) Matplotlib馆里,開發(fā)者可以僅需要幾行代碼,便可以生成繪圖可柿,直方圖鸠踪,功率譜,條形圖复斥,錯(cuò)誤圖营密,散點(diǎn)圖等。
官方網(wǎng)站http://matplotlib.org
- 用于創(chuàng)建出版質(zhì)量圖表的繪圖工具庫(kù)
- 最流行的Python底層繪圖庫(kù)目锭,主要做數(shù)據(jù)可視化圖表,名字取材于MATLAB评汰,模仿MATLAB構(gòu)建
- 目的是為Python構(gòu)建一個(gè)Matlab式的繪圖接口
- pyploy模塊包含了常用的matplotlib API函
線性圖
簡(jiǎn)單線性圖
在圖表的所有類型中,線性圖最為簡(jiǎn)單痢虹。線性圖的各個(gè)數(shù)據(jù)點(diǎn)由一條直線來(lái)連接. 一對(duì)對(duì)(x, y)值組成的數(shù)據(jù)點(diǎn)在圖表中的位置取決于兩條軸(x和y)的刻度范圍.
如果要繪制一系列的數(shù)據(jù)點(diǎn)被去,需要?jiǎng)?chuàng)建兩個(gè)Numpy數(shù)組. 首先, 創(chuàng)建包含x值的數(shù)組, 用作x軸. 再創(chuàng)建包含y值得數(shù)組,用作y軸. 完成了兩個(gè)數(shù)組創(chuàng)建奖唯,只需要調(diào)用plot()函數(shù)繪制圖像即可.
from matplotlib import pyplot as plt
import numpy as np
# 生成[0, 2π]之間的等間距的100個(gè)點(diǎn)
x = np.linspace(0, 2* np.pi,num=100)
y = np.sin(x)
plt.plot(x,y)
plt.show()
線條和標(biāo)記節(jié)點(diǎn)樣式: 標(biāo)記字符:標(biāo)記線條中的點(diǎn):
- 線條顏色惨缆,color='g'
- 線條風(fēng)格,linestyle='--'
- 線條粗細(xì)丰捷,linewidth=5.0
- 標(biāo)記風(fēng)格坯墨,marker='o'
- 標(biāo)記顏色,markerfacecolor='b'
- 標(biāo)記尺寸瓢阴,markersize=20
- 透明度畅蹂,alpha=0.5
-
線條和標(biāo)記節(jié)點(diǎn)格式字符 如果不設(shè)置顏色,系統(tǒng)默認(rèn)會(huì)取一個(gè)不同顏色來(lái)區(qū)別線條.
接下來(lái)我們繪制一個(gè)樣式較全的線形圖:
import numpy as np
import matplotlib.pyplot as plt
# 設(shè)置中文字體荣恐,否則中文會(huì)出現(xiàn)方框狀
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(0, 2* np.pi,num=10)
y = np.sin(x)
# 調(diào)用繪制線性圖函數(shù)plot()
plt.plot(x, y,
color='#3589FF', # 線的顏色
linestyle=':', # 線的風(fēng)格
linewidth=3, # 線的寬度
marker='o', # 標(biāo)記點(diǎn)的樣式
markerfacecolor='r', # 標(biāo)記點(diǎn)的顏色
markersize=10, # 標(biāo)記點(diǎn)的大小
alpha=0.7, # 圖形的透明度
label="cos(x)"
)
plt.show()
繪制多條折線
# 繪制多條折線
x = np.linspace(0, 2* np.pi,num=20)
y = np.sin(x)
# 調(diào)用繪制線性圖函數(shù)plot()
plt.plot(x, y,
color='#3589FF', # 線的顏色
linestyle=':', # 線的風(fēng)格
linewidth=3, # 線的寬度
marker='o', # 標(biāo)記點(diǎn)的樣式
markerfacecolor='r', # 標(biāo)記點(diǎn)的顏色
markersize=10, # 標(biāo)記點(diǎn)的大小
alpha=0.7, # 圖形的透明度
label="sin(x)" #設(shè)置圖例的label
)
siny = y.copy()
cosy = np.cos(x)
plt.plot(x, cosy,
color='y', # 線的顏色
linestyle='-', # 線的風(fēng)格
linewidth=3, # 線的寬度
marker='*', # 標(biāo)記點(diǎn)的樣式
markerfacecolor='b', # 標(biāo)記點(diǎn)的顏色
markersize=15, # 標(biāo)記點(diǎn)的大小
alpha=0.9, # 圖形的透明度
label="cos(x)" #設(shè)置圖例的label
)
# 設(shè)置x,y軸的label
plt.xlabel('時(shí)間(s)')
plt.ylabel('電壓(V)')
plt.legend()
plt.title('電壓隨時(shí)間變化的線性圖')
# 調(diào)用show方法顯式
plt.show()
將DataFrame繪制成線性圖
from pandas import DataFrame,Series
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
%matplotlib inline
data_frame = DataFrame({
'東軟熙康': np.random.randint(10, 100, 5),
'東軟醫(yī)療': np.random.randint(10, 100, 5),
'東軟睿道': np.random.randint(10, 100, 5),
})
plt.plot(data_frame, marker='o')
# 顯示圖例
plt.legend(data_frame, loc=2)
# 設(shè)置x軸刻度標(biāo)簽
plt.xticks([0, 1, 2, 3, 4], ['first', 'secod', 'third', 'forth', 'fifth'])
plt.title('東軟子公司1-5月份在職人員數(shù)量')
plt.xlabel('月份')
plt.ylabel('在職人數(shù)(百人)')
# True 顯示網(wǎng)格
# linestyle 設(shè)置線顯示的類型(一共四種)
# color 設(shè)置網(wǎng)格的顏色
# linewidth 設(shè)置網(wǎng)格的寬度
# plt.grid(True, linestyle = "-.", color = "r", linewidth = "3")
plt.grid()
# 顯示圖形
plt.show()
條狀圖
條狀圖也是非常常用的一種圖表類型.
條形圖是統(tǒng)計(jì)圖資料分析中最常用的圖形。主要特點(diǎn)有:
- 能夠使人們一眼看出各個(gè)各個(gè)項(xiàng)目數(shù)據(jù)的大小叠穆。
- 易于比較各個(gè)不同項(xiàng)目數(shù)據(jù)之間的差別少漆。
垂直條狀圖
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
index = np.arange(5)
values1 = np.random.randint(11, 20, 5)
values2 = np.random.randint(11, 20, 5)
values3 = np.random.randint(11, 20, 5)
# bar寬度
bar_width = 0.3
# 每一個(gè)bar占0.3寬度
plt.bar(index-bar_width, values1, width=bar_width, alpha=0.7, label='社保項(xiàng)目1', color='b')
plt.bar(index, values2, width=bar_width, alpha=0.7, label='社保項(xiàng)目2', color='r')
plt.bar(index+bar_width, values3, width=bar_width, alpha=0.7, label='社保項(xiàng)目3', color='g')
# 顯示圖例
plt.legend(loc=1)
# 設(shè)置X軸、Y軸數(shù)值范圍
# plt.xlim(-0.5, 5)
# plt.ylim(10, 20)
plt.axis([-0.6, 5, 10, 20])
# 設(shè)置x軸刻度標(biāo)簽 rotation旋轉(zhuǎn)角度
plt.xticks(index, ['社保項(xiàng)目'+str(ix) for ix in range(1, 6)], rotation=30)
# 設(shè)置標(biāo)題
plt.title('社保項(xiàng)目營(yíng)收', fontsize=20)
plt.xlabel('項(xiàng)目類型')
plt.ylabel('項(xiàng)目合同額(億元)')
# 顯示數(shù)值標(biāo)簽
for a,b in zip(index, values1):
plt.text(a-bar_width, b, '%.0f' % b, ha='center', va= 'bottom', fontsize=7)
for a,b in zip(index, values2):
plt.text(a, b, '%.0f' % b, ha='center', va= 'bottom', fontsize=7)
for a,b in zip(index, values3):
plt.text(a+bar_width, b, '%.0f' % b, ha='center', va= 'bottom', fontsize=7)
# 顯示網(wǎng)格
plt.grid()
plt.show()
水平條狀圖
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 繪制水平條狀圖
index = np.arange(5)
values1 = np.random.randint(10, 17, 5)
values2 = np.random.randint(10, 17, 5)
values3 = np.random.randint(10, 17, 5)
# 繪制條狀圖
bar_height = 0.3
plt.barh(index, values1, height=0.3, label='社保項(xiàng)目1', color='r')
plt.barh(index+bar_height, values2, height=0.3, label='社保項(xiàng)目2', color='b')
plt.barh(index+bar_height*2, values3, height=0.3, label='社保項(xiàng)目2', color='y')
# y軸標(biāo)簽
plt.yticks(index + bar_height, list('ABCDE'))
# 顯示數(shù)值標(biāo)簽
for a, b in zip(values1, index):
plt.text(a, b, '%.0f' % a, ha='left', va= 'center', fontsize=7)
for a, b in zip(values2, index):
plt.text(a, b+bar_height, '%.0f' % a, ha='left', va= 'center', fontsize=7)
for a, b in zip(values3, index):
plt.text(a, b+bar_height*2, '%.0f' % a, ha='left', va= 'center', fontsize=7)
# 設(shè)置標(biāo)題
plt.title('社保項(xiàng)目營(yíng)收', fontsize=20)
plt.xlabel('項(xiàng)目類型')
plt.ylabel('項(xiàng)目合同額(億元)')
plt.axis([0, 20, -0.4, 5])
plt.legend(loc=4)
plt.show()
餅圖
除了條狀圖, 餅圖也可以用來(lái)表示數(shù)據(jù).用pie()函數(shù)制作餅圖很簡(jiǎn)單.
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
%matplotlib inline
# 設(shè)置圖像大小
plt.figure(figsize=(9,9))
# 設(shè)置標(biāo)簽
labels = ['Java開發(fā)', '項(xiàng)目經(jīng)理', '測(cè)試運(yùn)維人員', 'Python開發(fā)', '架構(gòu)師']
# 標(biāo)簽對(duì)應(yīng)的值
values = [6000, 1000, 2000, 7000, 500]
# 每一個(gè)標(biāo)簽餅圖的顏色
colors = ['red', '#FEDD62', 'blue', 'gray', 'green']
# 那一塊內(nèi)容需要脫離餅圖凸顯, 可選值0-1
explode = [0.1, 0.1, 0, 0, 0]
# autopct='%1.1f%%'表示顯示百分比
# shadow顯示陰影
# startangle 正值表示逆時(shí)針旋轉(zhuǎn)
plt.pie(values,
labels=labels,
colors=colors,
explode=explode,
startangle=90,
shadow=True,
autopct='%1.1f%%')
# 設(shè)置為標(biāo)準(zhǔn)圓形
plt.axis('equal')
# 顯示圖例
plt.legend(loc=2)
plt.title('東軟軟件工程師人員職位占比')
plt.show()
散點(diǎn)圖
用兩組數(shù)據(jù)構(gòu)成多個(gè)坐標(biāo)點(diǎn)硼被,考察坐標(biāo)點(diǎn)的分布示损,判斷兩變量之間是否存在某種關(guān)聯(lián)或總結(jié)坐標(biāo)點(diǎn)的分布模式。散點(diǎn)圖將序列顯示為一組點(diǎn)嚷硫。值由點(diǎn)在圖表中的位置表示检访。類別由圖表中的不同標(biāo)記表示。散點(diǎn)圖通常用于比較跨類別的聚合數(shù)據(jù)仔掸。
簡(jiǎn)單的散點(diǎn)圖繪制
from matplotlib import pyplot as plt
import numpy as np
# 散點(diǎn) 橫軸和縱軸都是特征
x = np.random.normal(0, 1, 100) # 均值為0 方差為1 正態(tài)分布
y = np.random.normal(0, 1, 100)
plt.scatter(x, y)
plt.show()
x = np.random.normal(0, 1, 100000)
y = np.random.normal(0, 1, 100000)
plt.scatter(x, y)
plt.show()
x = np.random.normal(0, 1, 100000)
y = np.random.normal(0, 1, 100000)
plt.scatter(x, y,alpha=0.1)
plt.show()
案例:繪制機(jī)器學(xué)習(xí)中經(jīng)典數(shù)據(jù)集-鳶尾花
# 加載鳶尾花數(shù)據(jù)集
from sklearn import datasets
iris = datasets.load_iris()
iris.keys()
dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names'])
#print(iris.DESCR)
iris.feature_names
['sepal length (cm)',
'sepal width (cm)',
'petal length (cm)',
'petal width (cm)']
iris.target
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
iris.target_names
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
X = iris.data[:,:2]
y = iris.target
y
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
# type(X)
X[:,1]
plt.scatter(X[:,0],X[:,1])
X[y==0].size
100
len(X[y==0][:,0])
50
X[y==0,0] #散點(diǎn)圖的x軸 1是y軸
array([5.1, 4.9, 4.7, 4.6, 5. , 5.4, 4.6, 5. , 4.4, 4.9, 5.4, 4.8, 4.8,
4.3, 5.8, 5.7, 5.4, 5.1, 5.7, 5.1, 5.4, 5.1, 4.6, 5.1, 4.8, 5. ,
5. , 5.2, 5.2, 4.7, 4.8, 5.4, 5.2, 5.5, 4.9, 5. , 5.5, 4.9, 4.4,
5.1, 5. , 4.5, 4.4, 5. , 5.1, 4.8, 5.1, 4.6, 5.3, 5. ])
繪制萼片維度的散點(diǎn)圖
plt.scatter(X[y==0,0],X[y==0,1],color='r')
plt.scatter(X[y==1,0],X[y==1,1],color='g')
plt.scatter(X[y==2,0],X[y==2,1],color='b')
plt.scatter(X[y==0,0],X[y==0,1],color='r',marker='+')
plt.scatter(X[y==1,0],X[y==1,1],color='g',marker='x')
plt.scatter(X[y==2,0],X[y==2,1],color='b',marker='o')
花瓣維度的散點(diǎn)圖
X = iris.data[:,2:]
X
array([[1.4, 0.2],
[1.4, 0.2],
[1.3, 0.2],
X[y==0,0]
array([1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.6, 1.4,
1.1, 1.2, 1.5, 1.3, 1.4, 1.7, 1.5, 1.7, 1.5, 1. , 1.7, 1.9, 1.6,
1.6, 1.5, 1.4, 1.6, 1.6, 1.5, 1.5, 1.4, 1.5, 1.2, 1.3, 1.5, 1.3,
1.5, 1.3, 1.3, 1.3, 1.6, 1.9, 1.4, 1.6, 1.4, 1.5, 1.4])
plt.scatter(X[y==0,0],X[y==0,1],color='r',marker='o')
plt.scatter(X[y==1,0],X[y==1,1],color='g',marker='x')
plt.scatter(X[y==2,0],X[y==2,1],color='b',marker='+')
繪制多個(gè)圖像
在matplotlib中, 一張圖像是一個(gè)Figure對(duì)象. 在Figure對(duì)象中可以包含一個(gè)或者多個(gè)Axes對(duì)象蝗碎。每個(gè)Axes(ax)對(duì)象都是一個(gè)擁有自己坐標(biāo)系統(tǒng)的繪圖區(qū)域表鳍。我們可以通過(guò)subplot()函數(shù)(子圖)在一個(gè)Figure上創(chuàng)建多個(gè)圖像(Axes)
import numpy as np
import pandas as pd
from pandas import Series , DataFrame
import matplotlib.pyplot as plt
x = np.linspace(0.0,5.0)
y1 = np.sin(np.pi*x)
y2 = np.sin(np.pi*x*2)
# subplot(2,1,1) 2行一列的第一個(gè)圖
plt.subplot(2,1,1)
plt.ylabel('y1 value')
plt.plot(x, y1, 'b--')
plt.subplot(2,1,2)
plt.ylabel('y2 value')
plt.plot(x, y2, 'r--')
plt.xlabel('x value')
plt.show()
# 子圖位置可以進(jìn)行簡(jiǎn)寫
plt.subplot(221)
plt.plot(x,y1,'b--')
plt.subplot(222)
plt.plot(x,y2,'r--')
plt.subplot(223)
plt.plot(x,y1,'b*')
plt.subplot(224)
plt.plot(x,y2,'y--')
plt.show()
- 繪制子圖的另外一種寫法
# fig是畫布, ax是數(shù)據(jù)
fig, ax = plt.subplots(2,2)
fig, ax = plt.subplots(2,2)
ax[0][0].plot(x, y1)
ax[0][1].plot(x, y2)
ax[1][0].plot(x, y1)
ax[1][1].plot(x, y2)
plt.show()
其他可視化繪圖工具
- Seaborn
- Plotly
- pyecharts
- Bokeh
下面簡(jiǎn)單介紹一下Seaborn(選學(xué))
官方地址:http://seaborn.pydata.org/index.html
Seaborn其實(shí)是在matplotlib的基礎(chǔ)上進(jìn)行了更高級(jí)的API封裝,從而使得作圖更加容易,在大多數(shù)情況下使用seaborn就能做出很具有吸引力的圖笑窜,而使用matplotlib就能制作具有更多特色的圖。應(yīng)該把Seaborn視為matplotlib的補(bǔ)充蜈缤,而不是替代物缩滨。
Python中的一個(gè)制圖工具庫(kù),可以制作出吸引人的纸厉、信息量大的統(tǒng)計(jì)圖
在Matplotlib上構(gòu)建系吭,支持numpy和pandas的數(shù)據(jù)結(jié)構(gòu)可視化。
多個(gè)內(nèi)置主題及顏色主題
可視化單一變量颗品、二維變量用于比較數(shù)據(jù)集中各變量的分布情況
可視化線性回歸模型中的獨(dú)立變量及不獨(dú)立變量
案例演示
import numpy as np
import pandas as pd
from pandas import Series , DataFrame
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
df = sns.load_dataset('flights')
df.head()
df.shape
(144, 3)
# 對(duì)數(shù)據(jù)表進(jìn)行重塑 第一個(gè)index是重塑的新表的索引名稱是什么肯尺,第二個(gè)columns是重塑的新表的列名稱是什么,
#一般來(lái)說(shuō)就是被統(tǒng)計(jì)列的分組抛猫,第三個(gè)values就是生成新列的值應(yīng)該是多少
df = df.pivot(index='month',columns='year',values='passengers')
df
plt.figure(figsize=(15, 8))
sns.heatmap(df)
plt.show()
df.plot(figsize=(10,6))
plt.show()
plt.figure(figsize=(15, 8))
sns.heatmap(df,annot=True,fmt='d')
plt.show()
s = df.sum()
#柱狀圖的第一種寫法
plt.figure(figsize=(15, 8))
sns.barplot(s.index,s.values)
plt.show()
# 柱狀圖的第二種寫法
plt.figure(figsize=(15, 8))
s.plot(kind='bar')
plt.show()