Python 數據分析中常用的可視化工具
1 Matplotlib
用於創建出版質量圖表的繪圖工具庫,目的是為 Python 構建一個 Matlab 式的繪圖接口。
1.1 安裝
- Anaconada 自帶。
- pip 安裝
pip install matplotlib
1.2 引用
import matplotlib.pyplot as plt
1.3 常用方法
figure
Matplotlib 的圖像均位於 figure 對象中
- 創建 figure
fig = plt.figure()
subplot
fig.add_subplot(a,b,c)
- a,b 表示講 fig 分割成 axb 的區域
- c 表示當前選中要操作的區域,
注意 ·
:從 1 開始編號 - 返回的是 AxesSubplot 對象
- plot 繪圖的區域是最后一次指定 subplot 的位置(jupyter 里不能正確顯
示) - 同時返回新創建的 figure 和 subplot 對象數組
fig,subplot arr=plt.subplots(2,2)
在 jupyter 里可以正常顯示,推薦使用這種方式創建多個圖表
plt.plot()
作圖方法。
# 在指定 subplot 作圖
import scipy as sp
from scipy import stats
x = np.linspace(-5, 15, 50)
#print x.shape
# 繪制高斯分布
plt.plot(x, sp.stats.norm.pdf(x=x, loc=5, scale=2))
# 疊加直方圖
plt.hist(sp.stats.norm.rvs(loc=5, scale=2, size=200), bins=50, normed=True, color='red', alpha=0.5)
plt.show()
繪制直方圖
plt.hist(np.random.randn(100), bins=10, color='b', alpha=0.3)
繪制散點圖
x = np.arange(50)
y = x + 5 * np.random.rand(50)
plt.scatter(x, y)
柱狀圖
x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.25
ax = plt.subplot(1,1,1)
ax.bar(x, y1, width, color='r')
ax.bar(x+width, y2, width, color='g')
ax.set_xticks(x+width)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
plt.show()
矩陣繪圖
m = np.random.rand(10,10)
print(m)
plt.imshow(m, interpolation='nearest', cmap=plt.cm.ocean)
plt.colorbar()
plt.show()
顏色 標記 線型
ax.plot(x,y,'r--')
== ax.plotx,y,linestyle=--',color=r')
刻度、標簽、圖例
- 設置刻度范圍
plt.xlim(),plt.ylim()
ax.set_xlim(),ax.set_ylim()
- 設置顯示的刻度
plt.xticks(),plt.yticks()
ax.set_xticks(),ax.set yticks)
- 設置刻度標簽
ax.set_xticklabels(),ax.set yticklabels()
- 設置坐標軸標簽
- `ax.set_xlabel(),ax.set ylabel0()
- 設置標題
ax.set title()
- 圖例
ax.plot(label=legend')
ax.legend),plt.legend()
loc=‘best'
自動選擇放置圖例最佳位置
matplotlib 設置
plt.rc()
1.4 3D 繪圖
matplotlib 支持 3D 繪圖
下面代碼給出了不同年份中,不同國家的平均壽命。
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import numpy as np
import matplotlib; matplotlib.style.use('ggplot')
%matplotlib inline
# 讀取 csv 數據集
lexp = pd.read_csv('lexpectancy.csv')
lexp.dropna(inplace=True)
lexp.reset_index(inplace=True)
plot_data = lexp[['Country', '1960', '1970', '1980', '1990', '2000']][:3]
print(plot_data)
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
country_list = plot_data['Country'].values.tolist()
year_list = ['1960', '1970', '1980', '1990', '2000']
for i, (color, z) in enumerate(zip(['r', 'g', 'b'], [0, 10, 20])):
age_list = plot_data.iloc[i][1:].values.tolist()
xs = np.arange(len(age_list))
ys = age_list
cs = [color] * len(age_list)
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
ax.set_xticklabels(year_list)
ax.set_yticks([0, 10, 20])
ax.set_yticklabels(country_list)
ax.set_xlabel('Year')
ax.set_ylabel('Country')
ax.set_zlabel('Age')
更多參考 mplot3d tutorial
2 Seaborn
什么是 Seaborn
- Python 中的一個制圖工具庫,可以制作出吸引人的、信息量大的統計圖
- 在 Matplotlib 上構建,支持 numpy 和 pandas 的數據結構可視化,甚至是 scipy 和 statsmodels 的統計模型可視化
特點
- 多個 內置主題 及顏色主題
- 可視化 單一變量、二維變量 用於 比較 數據集中各變量的分布情況
- 可視化 線性回歸模型 中的 獨立變量 及不獨立變量
- 可視化矩陣數據,通過聚類算法探究矩陣間的結構
- 可視化 時間序列數據 及不確定性的展示
- 可在 分割區域制圖,用於復雜 的可視化
2.2 安裝
conda 安裝:conda install seaborn
pip 安裝:pip install seaborn
2.3 引用
import seaborn as sns
2.4 數據集分布可視化
- 單變量分布
sns.distplot)
- 直方圖
sns.distplot(kde=False)
- 核密度估計
sns.distplot(hist=False)或 sns.kdeplot)
- 擬合參數分布
sns.distplot(kde=False,fit=)
- 直方圖
- 雙變量分布
- 散布圖
sns.jointplot0
- 二維直方圖
Hexbin sns.jointplot(kind=‘hex)
- 核密度估計
sns.jointplot(kind=‘kde')
- 散布圖
- 數據集中變量間關系可視化
sns.pairplot()
2.5 類別數據可視化
- 類別散布圖
sns.stripplot()
數據點會重疊sns.swarmplot()
數據點避免重疊- hue 指定子類別
- 類別內數據分布
- 盒子圖
sns.boxplot()
,hue 指定子類別 - 小提琴圖
sns.violinplot()
,hue 指定子類別
- 盒子圖
- 類別內統計圖
- 柱狀圖
sns.barplot()
- 點圖
sns.pointplot()
- 柱狀圖
3 Bokeh
什么是 Bokeh
- 專門針對 Web 瀏覽器的交互式、可視化 Python 繪圖庫
- 可以做出像 D3.,js 簡潔漂亮的交互可視化效果
特點
- 獨立的 HTML 文檔或服務端程序
- 可以處理大量、動態或數據流
- 支持 Python(或 Scala,R,Julia.)
- 不需要使用 Javascript
Bokeh 接口
- Charts:高層接口,以簡單的方式繪制復雜的統計圖
- Plotting:中層接口,用於組裝圖形元素
- Models:底層接口,為開發者提供了最大的靈活性
3.1 安裝
conda 安裝:conda install bokeh
pip 安裝:pip install bokeh
3.2 引用
- 生成. html 文檔
from bokeh.io import output file
- 在 jupyter 中使用
from boken.io import output_notebook
3.3 bokeh.charts
引用和導入數據
# 引用
from bokeh.io import output_notebook, output_file, show
from bokeh.charts import Scatter, Bar, BoxPlot, Chord
from bokeh.layouts import row
import seaborn as sns
# 導入數據
exercise = sns.load_dataset('exercise')
# 在使用 Jupyter notebook 時設置
output_notebook()
散點圖
p = Scatter(data=exercise, x='id', y='pulse', title='exercise dataset')
show(p)
柱狀圖
p = Bar(data=exercise, values='pulse', label='diet', stack='kind', title='exercise dataset')
show(p)
盒子圖
box1 = BoxPlot(data=exercise, values='pulse', label='diet', color='diet', title='exercise dataset')
box2 = BoxPlot(data=exercise, values='pulse', label='diet', stack='kind', color='kind', title='exercise dataset')
show(row(box1, box2)) # 顯示兩張圖
弦圖 Chord
- 展示多個節點之間的聯系
- 連線的粗細代表權重
chord1 = Chord(data=exercise, source="id", target="kind")
# value 設置以什么為粗細
chord2 = Chord(data=exercise, source="id", target="kind", value="pulse")
show(row(chord1, chord2))
更多參考:Bokeh 官網
3.4 bokeh.plotting
from bokeh.plotting import figure
import numpy as np
p = figure(plot_width=400, plot_height=400)
# 方框
p.square(np.random.randint(1,10,5), np.random.randint(1,10,5), size=20, color="navy")
# 圓形
p.circle(np.random.randint(1,10,5), np.random.randint(1,10,5), size=10, color="green")
show(p)
更多圖形元素參考:Bokeh 官網