10行程式碼告訴你,為什麼說Python資料視覺化是一件藝術品
1. 畫散點圖
畫散點圖用plt.scatter(x,y)。畫連續曲線在下一個例子中可以看到,用到了plt.plot(x,y)。
plt.xticks(loc,label)可以自定義x軸刻度的顯示,第一個引數表示的是第二個引數label顯示的位置loc。
plt.autoscale(tight=True)可以自動調整影象顯示的最佳化比例 。
plt.scatter(x,y) plt.title("Web traffic") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.xticks([w*7*24 for w in range(10)],['week %i' %w for w in range(10)]) plt.autoscale(tight=True) plt.grid() ##plt.show()1234567812345678
畫出散點圖如下:
2. 多項式擬合併畫出擬合曲線
## 多項式擬合
fp2 = np.polyfit(x,y,3)
f2 = np.poly1d(fp2)
fx = np.linspace(0,x[-1],1000)
plt.plot(fx,f2(fx),linewidth=4,color='g')
## f2.order: 函式的階數
plt.legend(["d=%i" % f2.order],loc="upper right")
plt.show()123456789123456789
效果圖:
3. 畫多個子圖
這裡用到的是sklearn的iris_dataset(鳶尾花資料集)。
此資料集包含四列,分別是鳶尾花的四個特徵:
sepal length (cm)——花萼長度
sepal width (cm)——花萼寬度
petal length (cm)——花瓣長度
petal width (cm)——花瓣寬度
# -*- coding=utf-8 -*- from matplotlib import pyplot as plt from sklearn.datasets import load_iris import numpy as np import itertools data = load_iris() #print(data.data) #print(data.feature_names) #print(data.target) features = data['data'] feature_names = data['feature_names'] target = data['target'] labels = data['target_names'][data['target']] print(data.data) print(data.feature_names)123456789101112131415161718123456789101112131415161718
這裡有一個排列組合參考程式碼,最後是取出了兩兩組合的情況。
排列組合的結果是feature_names_2包含了排列組合的所有情況,它的每一個元素包含了一個排列組合的所有情況,比如第一個元素包含了所有單個元素排列組合的情況,第二個元素包含了所有的兩兩組合的情況……所以這裡取出了第二個元素,也就是所有的兩兩組合的情況
feature_names_2 = []
#排列組合
for i in range(1,len(feature_names)+1):
iter = itertools.combinations(feature_names,i)
feature_names_2.append(list(iter))
print(len(feature_names_2[1]))
for i in feature_names_2[1]:
print(i)123456789123456789
下面是在for迴圈裡畫多個子圖的方法。對我來說,這裡需要學習的有不少。比如
for i,k in enumerate(feature_names_2[1]):這一句老是記不住。
比如從列表中取出某元素所在的索引的方法:index1 = feature_names.index(k[0]),也即index = list.index(element)的形式。
比如for迴圈的下面這用法:for t,marker,c in zip(range(3),”>ox”,”rgb”):
plt.figure(1)
for i,k in enumerate(feature_names_2[1]):
index1 = feature_names.index(k[0])
index2 = feature_names.index(k[1])
plt.subplot(2,3,1+i)
for t,marker,c in zip(range(3),">ox","rgb"):
plt.scatter(features[target==t,index1],features[target==t,index2],marker=marker,c=c)
plt.xlabel(k[0])
plt.ylabel(k[1])
plt.xticks([])
plt.yticks([])
plt.autoscale()
plt.tight_layout()
plt.show()12345678910111213141234567891011121314
這裡的視覺化效果如下:
4. 畫水平線和垂直線
比如在上面最後一幅圖中,找到了一種方法可以把三種鳶尾花分出來,這是我們需要畫出模型。這個時候怎麼畫呢?
plt.figure(2)
for t,marker,c in zip(range(3),">ox","rgb"):
plt.scatter(features[target==t,3],features[target==t,2],marker=marker,c=c)
plt.xlabel(feature_names[3])
plt.ylabel(feature_names[2])
# plt.xticks([])
# plt.yticks([])
plt.autoscale()
plt.vlines(1.6, 0, 8, colors = "c",linewidth=4,linestyles = "dashed")
plt.hlines(2.5, 0, 2.5, colors = "y",linewidth=4,linestyles = "dashed")
plt.show() 12345678910111234567891011
此時視覺化效果如下:
5. 動態畫圖
plt.ion()開啟互動模式。plt.show()不再阻塞程式執行。
注意plt.axis()的用法。
plt.axis([0, 100, 0, 1])
plt.ion()
for i in range(100):
y = np.random.random()
plt.autoscale()
plt.scatter(i, y)
plt.pause(0.01)1234567812345678
視覺化效果: