5個案例教你用Python玩轉資料視覺化
1、選擇Seaborn的調色盤
Seaborn的調色盤和matplotlib的顏色表類似。色彩可以幫助你發現數據中的模式,也是重要的視覺化組成部分。Seaborn有很豐富的調色盤,在這個示例中會將其視覺化。
操作步驟
(1)匯入部分如下:
import seaborn as sns import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from dautil import plotting
(2)使用以下函式幫助繪製調色盤:
def plot_palette(ax, plotter, pal, i, label, ncol=1): n = len(pal) x = np.linspace(0.0, 1.0, n) y = np.arange(n) + i*n ax.scatter(x, y, c=x, cmap=mpl.colors.ListedColormap(list(pal)), s=200) plotter.plot(x,y,label=label) handles, labels = ax.get_legend_handles_labels() ax.legend(loc='best', ncol=ncol, fontsize=18)
(3)分類調色盤(categorical palette)對於分類資料很有用,例如性別、血型等。以下函式可以繪製一些Seaborn的分類調色盤:
def plot_categorical_palettes(ax): palettes = ['deep', 'muted', 'pastel', 'bright', 'dark','colorblind'] plotter = plotting.CyclePlotter(ax) ax.set_title('Categorical Palettes') for i, p in enumerate(palettes): pal = sns.color_palette(p) plot_palette(ax, plotter, pal, i, p, 4)
(4)圓形色彩系統(circular color system)通常用HLS(色度亮度飽和度,Hue Lightness Saturation)來取代RGB(紅綠藍Red Gree Blue)顏色空間。如果你有很多分類這將會很有用。以下函式可以使用HLS系統繪製調色盤。
def plot_circular_palettes(ax): ax.set_title('Circular Palettes') plotter = plotting.CyclePlotter(ax) pal = sns.color_palette("hls", 6) plot_palette(ax, plotter, pal, 0, 'hls') sns.hls_palette(6, l=.3, s=.8) plot_palette(ax, plotter, pal, 1, 'hls l=.3 s=.8') pal = sns.color_palette("husl", 6) plot_palette(ax, plotter, pal, 2, 'husl') sns.husl_palette(6, l=.3, s=.8) plot_palette(ax, plotter, pal, 3, 'husl l=.3 s=.8')
(5)Seaborn也有基於線上的ColorBrewer工具的調色盤( http://colorbrewer2.org/ )。用以下函式繪製出來:
def plot_brewer_palettes(ax): ax.set_title('Brewer Palettes') plotter = plotting.CyclePlotter(ax) pal = sns.color_palette("Paired") plot_palette(ax, plotter, pal, 0, 'Paired') pal = sns.color_palette("Set2", 6) plot_palette(ax, plotter, pal, 1, 'Set2')
(6)連續調色盤(sequential palettes)對於資料範圍很廣的資料來說很有用,比如說有數量級差異的資料。用以下函式繪製出來:
def plot_sequential_palettes(ax): ax.set_title('Sequential Palettes') plotter = plotting.CyclePlotter(ax) pal = sns.color_palette("Blues") plot_palette(ax, plotter, pal, 0, 'Blues') pal = sns.color_palette("BuGn_r") plot_palette(ax, plotter, pal, 1, 'BuGn_r') pal = sns.color_palette("GnBu_d") plot_palette(ax, plotter, pal, 2, 'GnBu_d') pal = sns.color_palette("cubehelix", 6) plot_palette(ax, plotter, pal, 3, 'cubehelix')
(7)以下幾行程式碼呼叫了我們之前定義的函式:
%matplotlib inline fig, axes = plt.subplots(2, 2, figsize=(16, 12)) plot_categorical_palettes(axes[0][0]) plot_circular_palettes(axes[0][1]) plot_brewer_palettes(axes[1][0]) plot_sequential_palettes(axes[1][1]) plotting.hide_axes(axes) plt.tight_layout()
請參見以下截圖瞭解最終結果:

image
2、選擇matplotlib的顏色表
matplotlib的顏色表最近受到了很多批評,因為它們可能會誤導使用者,但是在我看來大多數的顏色表還是不錯的。預設的顏色表在matplotlib 2.0中有一些改進,可以在這裡檢視:
http://matplotlib.org/style_changes.html
當然,有些matplotlib的顏色表不支援一些不錯的引數,比如說jet。在藝術中,就像資料分析中一樣,幾乎沒有什麼東西是絕對正確的,所以這裡就交給讀者去判斷。
實際上,我覺得考慮如何解決印刷出版物以及各種各樣的色盲問題是很重要的。在這個示例中我將用色條來視覺化相對安全的顏色表。這裡使用到的是matplotlib眾多顏色表中的很小一部分。
操作步驟
(1)匯入部分如下:
import matplotlib.pyplot as plt import matplotlib as mpl from dautil import plotting
(2)通過以下程式碼畫出資料集:
fig, axes = plt.subplots(4, 4) cmaps = ['autumn', 'spring', 'summer', 'winter', 'Reds', 'Blues', 'Greens', 'Purples', 'Oranges', 'pink', 'Greys', 'gray', 'binary', 'bone', 'hot', 'cool'] for ax, cm in zip(axes.ravel(), cmaps): cmap = plt.cm.get_cmap(cm) cb = mpl.colorbar.ColorbarBase(ax, cmap=cmap, orientation='horizontal') cb.set_label(cm) ax.xaxis.set_ticklabels([]) plt.tight_layout() plt.show()
請參見以下截圖瞭解最終結果:

image
3、檢視散點圖矩陣
如果你的資料集中變數不是很多,那麼檢視你資料所有的散點圖是個不錯的主意。通過呼叫Seaborn或者pandas的一個函式就可以做到。這些函式會展示一個矩陣的核密度估計圖或對角線上的直方圖。
Python學習群:556370268,有大牛答疑,有資源共享!是一個非常不錯的交流基地!歡迎喜歡Python的小夥伴!
操作步驟
(1)匯入部分如下:
import pandas as pd from dautil import data from dautil import ts import matplotlib.pyplot as plt import seaborn as sns import matplotlib as mpl
(2)以下幾行程式碼載入天氣資料:
df = data.Weather.load() df = ts.groupby_yday(df).mean() df.columns = [data.Weather.get_header(c) for c in df.columns]
(3)用Seaborn的pairplot()函式繪製圖形,這個函式預設繪製對角線上的直方圖:
%matplotlib inline # Seaborn plotting, issues due to NaNs sns.pairplot(df.fillna(0))
結果如下所示:

image
(4)通過pandas的scatter_matrix()函式生成一個類似的圖形,並請求對角線上的核密度估計圖:
sns.set({'figure.figsize': '16, 12'}) mpl.rcParams['axes.linewidth'] = 9 mpl.rcParams['lines.linewidth'] = 2 plots = pd.scatter_matrix(df, marker='o', diagonal='kde') plt.show()
請參見以下截圖瞭解最終結果:

image
4、通過mpld3使用d3.js進行視覺化
d3.js是在2011年推出的一個JavaScript資料視覺化庫,我們可以在IPython Notebook裡面使用這個庫。我們將在一個普通matplotlib圖上新增一個懸浮工具提示。這裡我們會使用mpld3包作為使用d3.js的橋樑。這個示例不需要任何JavaScript程式設計。
1. 準備工作
通過以下命令安裝mpld3 0.2:
$ [sudo] pip install mpld3
2. 操作步驟
(1)由匯入開始,並啟用mpld3:
%matplotlib inline import matplotlib.pyplot as plt import mpld3 mpld3.enable_notebook() from mpld3 import plugins import seaborn as sns from dautil import data from dautil import ts
(2)載入天氣資料並按照下面的方法將其繪製出來:
df = data.Weather.load() df = df[['TEMP', 'WIND_SPEED']] df = ts.groupby_yday(df).mean() fig, ax = plt.subplots() ax.set_title('Averages Grouped by Day of Year') points = ax.scatter(df['TEMP'], df['WIND_SPEED'], s=30, alpha=0.3) ax.set_xlabel(data.Weather.get_header('TEMP')) ax.set_ylabel(data.Weather.get_header('WIND_SPEED')) labels = ["Day of year ".format(i) for i in range(366)] tooltip = plugins.PointLabelTooltip(points, labels) plugins.connect(fig, tooltip)
高亮顯示的那一行是工具欄。在下面的截圖中,我們可以看到“Day of year 31”文字來自這個工具欄:

image
如你所見,在這個圖形的底部,還有可以平移和縮放圖形的裝置。
5、把箱線圖、核密度圖和小提琴圖組合
小提琴圖(Violin Plot)是一種組合盒圖和核密度圖或直方圖的圖形型別。Seaborn和matplotlib都能提供小提琴圖。在這個示例中我們將使用Seaborn來繪製天氣資料的Z分數(標準分數),分數的標準化並不是必需的,但是如果沒有它的話小提琴圖會很發散。
Python學習群:556370268,有大牛答疑,有資源共享!是一個非常不錯的交流基地!歡迎喜歡Python的小夥伴!
操作步驟
(1)匯入部分如下:
import seaborn as sns from dautil import data import matplotlib.pyplot as plt
(2)載入天氣資料並計算標準分數:
df = data.Weather.load() zscores = (df - df.mean())/df.std()
(3)繪製標準分數的小提琴圖:
%matplotlib inline plt.figure() plt.title('Weather Violin Plot') sns.violinplot(zscores.resample('M').mean()) plt.ylabel('Z-scores')
第一個小提琴圖如下所示:

image
(4)繪製雨天和旱天相對風速的小提琴圖:
plt.figure() plt.title('Rainy Weather vs Wind Speed') categorical = df categorical['RAIN'] = categorical['RAIN'] > 0 ax = sns.violinplot(x="RAIN", y="WIND_SPEED",data=categorical)
第二個小提琴圖如下所示:

image