深入浅出统计学 第一章 数据的可视化
序言
在深入淺出統計學的第一張中一共出現了4類圖像:
1. 比較基本比例—>餅圖
2. 比較數值的高低條形圖(基本條形圖,堆積條形圖,分段條形圖)
3. 連續數據的對比(等距直方圖—>頻數,非等距直方圖—>頻數密度)
4. 截止到某時間點的累計總量—>累積頻數圖
Python中是實現方式有兩種,matplotlib和Pandas,一般而言直接使用Pandas即可.此處我們先給出Pandas中的實現,然后再做部分補充.數據我們依然使用數據探索那篇文章中用過的UCI紅酒質量數據集.
本處最后區域圖與散點圖,六邊形容器圖代碼與文字基本來自于Pandas的文檔,僅僅略加修改,鏈接請參見文章末尾.
讀取數據
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline# 定義讀取數據的函數 def ReadAndSaveDataByPandas(target_url = None,file_save_path = None ,save=False):if target_url !=None:target_url = ("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv") if file_save_path != None:file_save_path = "/home/fonttian/Data/UCI/Glass/glass.csv"wine = pd.read_csv(target_url, header=0, sep=";")if save == True:wine.to_csv(file_save_path, index=False)return winedef GetDataByPandas():wine = pd.read_csv("/home/font/Data/UCI/WINE/wine.csv")y = np.array(wine.quality)X = np.array(wine.drop("quality", axis=1))# X = np.array(wine)columns = np.array(wine.columns)return X, y, columns# X,y,names = GetDataByPandas() # wine = pd.DataFrame(X) wine = pd.read_csv("/home/font/Data/UCI/WINE/wine.csv") print(list(wine.columns))print(set(wine['quality'].value_counts())) print(wine['quality'].value_counts()) wine['quality'].value_counts().plot.pie(subplots=True,figsize=(8,8)) plt.show() ['fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol', 'quality'] {199, 681, 10, 18, 53, 638} 5 681 6 638 7 199 4 53 8 18 3 10 Name: quality, dtype: int64 df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y']) print(df) df.plot.pie(subplots=True, figsize=(16,8 )) df.plot.pie(subplots=True,labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'],autopct='%.2f', fontsize=20, figsize=(16, 8)) plt.show() x y a 0.357865 0.423390 b 2.318759 2.089677 c 0.464072 0.502673 d 1.140500 2.779330 wine['quality'][0:10].plot(kind='bar',figsize=(16,8)); plt.axhline(0, color='k') plt.show() wine[['residual sugar','pH','quality']][0:10].plot.bar(figsize=(16,8)) wine[['residual sugar','pH']][0:10].plot.bar(figsize=(16,8),stacked=True) wine[['residual sugar','pH']][0:10].plot.barh(figsize=(16,8),stacked=True) plt.show() # 普通畫法 wine[['residual sugar','alcohol']].plot.hist(bin==20,figsize=(16,10),alpha=0.5) # 分開畫 wine[['residual sugar','alcohol']].hist(color='k', alpha=0.5, bins=50,figsize=(16,10)) plt.show() df_hist = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c']) df_hist.plot.hist(alpha=0.5) plt.show() # orientation='horizontal', 斜向 # cumulative=True, 是否累積 df_hist['b'].plot.hist(orientation='horizontal', cumulative=True) plt.show() wine[['fixed acidity', 'residual sugar', 'alcohol', 'quality']][0:15].plot() wine[['fixed acidity', 'residual sugar', 'alcohol', 'quality']][0:15].cumsum().plot() plt.show()其他的常用圖形
除了這幾種圖像之外,Pandas還提供了很多種其他的數據可視化方法,這里我們介紹其中較為簡單和常用的幾種余下的幾種會在機器學習的數據探索中介紹,之前已經寫過一篇簡單的入門,余下內容日后補充—>https://blog.csdn.net/FontThrone/article/details/78188401
三種圖像的作用
1. 箱型圖 ---> 展示數據分布,發現異常點 2. 兩種區域圖 ---> 對比數據大小 3. 散點圖,六邊形容器圖 ---> 數據分布與趨勢1.箱型圖
在豎向的箱型圖中從上到下的五個橫線分別是,上界,上四分位數,中位數,下四分位數,下界,上下界以外的點可作為異常點的一個參考,這個圖形在書中第三章有將為詳細的解釋
2.區域圖
疊加與非疊加區域圖,有點在于可以更好地比較區域(x * y)的大小
3.散點圖與六邊形容器圖
可以一定程度上觀察數據分布,比如發現數據分布的區域和分布趨勢,對于發現數據分布的區域,或者找到一定的擬合規律還是有很大幫助的.有必要的話,還可以使用三維散點圖,但是這需要matplotlib實現.
wine[['fixed acidity', 'residual sugar', 'alcohol', 'quality']].plot.box()# vert=False, 橫向 # positions=[1, 4, 6, 8], y軸位置 # color=color, 顏色 # sym='r+', 異常點的樣式 color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray') wine[['fixed acidity', 'residual sugar', 'alcohol', 'quality']].plot.box(vert=False, positions=[1, 4, 6, 8],color=color,sym='r+') plt.show()# pandas 自帶接口 ----> boxplot(),此處不再演示 wine[['fixed acidity', 'residual sugar', 'alcohol', 'quality']][0:15].plot.area() wine[['fixed acidity', 'residual sugar', 'alcohol', 'quality']][0:15].plot.area(stacked=False) plt.show() # 可以使用DataFrame.plot.scatter()方法繪制散點圖。散點圖需要x和y軸的數字列。這些可以分別由x和y關鍵字指定。 df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd']) df.plot.scatter(x='a', y='b');# 要在單個軸上繪制多個列組,請重復指定目標ax的plot方法。建議使用color和label關鍵字來區分每個組。 ax = df.plot.scatter(x='a', y='b', color='black', label='Group 1'); df.plot.scatter(x='c', y='d', color='red', label='Group 2', ax=ax); # 可以給出關鍵字c作為列的名稱以為每個點提供顏色: # 您可以傳遞matplotlib scatter支持的其他關鍵字。以下示例顯示了使用數據框列值作為氣泡大小的氣泡圖。 df.plot.scatter(x='a', y='b', c='c', s=50); df.plot.scatter(x='a', y='b', s=df['c']*200);您可以使用DataFrame.plot.hexbin()創建六邊形箱圖。如果數據過于密集而無法單獨繪制每個點,則Hexbin圖可能是散點圖的有用替代方案。
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])df['b'] = df['b'] + np.arange(1000)df.plot.hexbin(x='a', y='b', gridsize=25,figsize=(16,10))plt.show()一個有用的關鍵字參數是gridsize;它控制x方向上的六邊形數量,默認為100。更大的gridsize意味著更多,更小的分組。
默認情況下,計算每個(x, y)點周圍計數的直方圖。您可以通過將值傳遞給C和reduce_C_function參數來指定替代聚合。C specifies the value at each (x, y) point and reduce_C_function is a function of one argument that reduces all the values in a bin to a single number (e.g. mean, max, sum, std). 在這個例子中,位置由列a和b給出,而值由列z給出。箱子與numpy的max函數聚合。
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])df['b'] = df['b'] = df['b'] + np.arange(1000)df['z'] = np.random.uniform(0, 3, 1000)df.plot.hexbin(x='a', y='b', C='z', reduce_C_function=np.max,gridsize=25,figsize=(16,10))plt.show()參考文章
1.Pandas0.19.2 中文文檔 可視化
2.Pandas最新文檔 可視化
3.本人去年寫的數據探索入門級文章
總結
以上是生活随笔為你收集整理的深入浅出统计学 第一章 数据的可视化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu16.04 安装R与RStu
- 下一篇: Python实现 灰色关联分析 与结果可