繪圖和可視化 Matplotlib,Pandas,Sseaborn, Pyecharts(數據蛙視頻課摘錄)


數據蛙視頻教程摘錄

點擊:《git上總結可視化知識大全

 

附加-數據可視化之美:

例子:地鐵圖,擬真距離,這是因為乘客關心的是從起點到終點,需要換乘哪幾條線最方便,不會考慮行進了多少公里。所以地鐵圖,是一定程度上的模擬真實距離,但不是完全真實,不像baidu地圖上左下腳有圖標:一條橫線表示距離。

  • 讓數據更高效的被閱讀
  • 突出數據背后的規律
  • 突出重要因素
  • 最后是美觀。

 

基礎概念:

  • Dimension: 描述分析的角度,數學,分類數據,(時間,地理位置,產品類型)
  • Measure:  數值 (元,銷量,金額等 )

 

 

 

 

 

 跟蹤app/網站用戶的點擊瀏覽路徑。

 

 

揭示折線看不出來的規律。

 

 

社交關系

業績目標

大數據分析,文本分析利器。

 

 

地理圖:pyecharts上可以繪制動態地理圖

 

 

三個繪圖工具:

  1. matplotlib繪圖。(遇到復雜的制圖需求時使用,最基礎的庫,所以每個函數的參數非常多並且復雜)
  2. pandas plot API。(日常繪圖使用pandas足夠了✅),優化matplotlib, 更方便繪圖。
  3. seaborn繪制統計圖形。
    •   基於matplotlib和pandas, 更高級,做了優化,可視化效果更好,
    •   專業用於統計分析。
  • ⚠️:可視化課程的重點是:利用圖形去理解數據,而不是注重圖形的美觀。

 

目錄


 

Matplotlib

--Hello World

matplotlib.pyplot

matplotlib.pyplot is a state-based interface to matplotlib. It provides a MATLAB-like way of plotting.

基於狀態的接口,提供類似MATLAB樣式的繪圖工具。(MATLAB是收費繪圖軟件)

 

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0, 2*np.pi, 100) Y = np.sin(X) Y1 = np.cos(X) plt.title("Hello World!")  #給圖形命名
plt.plot(X,Y)              #畫一個圖
plt.plot(X,Y1) 

生成:

第一行是儲存的內存位置。

 

plt.show() #使用show函數可以生成畫布 

 

分開畫2個圖:

X = np.linspace(0,2*np.pi, 100)
Y = np.sin(X)
plt.subplot(2,1, 1)   #為當前figure附加一個子畫布。
plt.plot(X,Y)      

plt.subplot(2,1,2)
plt.plot(X, np.cos(X), color = 'r')

解釋:

subplot(nrows, ncols, index, **kwargs)
  • index是圖的位置索引。
  • nrows, ncols是figure的行和列的數量,比如2行*2列,生成4塊畫布。

  

3 Bar Chart

一般用於表示種類的數據。

  • bar()
  • barh(),橫向排列bar。
data = [5,25,50,20]
plt.bar(range(len(data)), data)
#<BarContainer object of 4 artists> 

 

3.03多個bar

data =[[5,25,50,20], [4,23,51,17],[6,22,52,19]] #2維數據。
X =np.arange(4)

plt.bar(X+0.00, data[0], color='b', width=0.25, label="A")
plt.bar(X+0.25, data[1], color='g', width=0.25, label="B")
plt.bar(X+0.50, data[2], color='r', width=0.25, label="C")

plt.legend() #圖上顯示標簽

 

 

3.04 stacked

⚠️:bottom參數的作用就是當一個基座。新的數據的圖從基座上繪制。

data[0]+np.array(data[1])
#array([  9,  48, 101,  37])

 

3.05 scatter

A scatter plot of y vs x with varying marker size and/or color

用於描述2個連續變量之間的關系。

matplotlib.pyplot.scatter(xys=Nonec=Nonemarker=None  alpha=None , data=None**kwargs

  • s參數:scalar, The marker size in points**2.
  • c參數: color, sequence, or sequence of color
  • alpha參數,表示圖像的透明度,希臘第一個字母。The alpha blending value, between 0 (transparent) and 1 (opaque). 從透明到渾濁。
# ⚠️x, y ,colors, area的索引是一一對應的。
N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.randn(N)
# colors = np.random.randint(0,2, size=50) #根據數據分成2種顏色
area
= np.pi * (15*np.random.rand(N))**2 #調整大小 plt.scatter(x,y, c=colors, alpha=0.5, s=area)

 

3.06Histogram 直方圖

用來衡量連續變量的概率分布。首先要定義bins(值的范圍),需要把連續值分成不同等份,然后計算每一份里面數據的數量。

 

a = np.random.randn(10000) plt.hist(a, bins=100)  #繪制一個直方圖, 參數bins分成100組。
plt.show() #plt.ylim(0,20) #Get or set the y-limits of the current axes. ylim(bottom, top)

一千個符合正態分布的數據,根據極值,分成100組,每組的數據量越大,圖上顯示的就越高。

 

6.boxplots

boxplots用於表達連續特征的百分位數分布。統計學上經常被用於檢測單變量的異常值,或者用於檢測離散特征和連續特征的關系。

x = np.random.randint(20,100, size=(30,3)) plt.boxplot(x) plt.ylim(0,120) #設置y的值范圍120. plt.xticks([1,2,3], ["label_a", 'label_b', 'label_c'])  # xticks在x軸設置標簽。

 

 

如何在圖上繪制是否是中位數?

np.median(x, axis=0) #行方向的中位數
#array([55.5, 64. , 63. ])
np.mean(x,axis = 0)

 

上面的代碼,增加一行:

plt.hlines(y=np.median(x, axis=0)[0], xmin=0, xmax = 4)  #hlines()用於在圖上畫一條水平方向的線

 

7 colors/texts/annotate

使用顏色: 顏色可以用gbp,也可以使用自帶的。

fig, ax = plt.subplots(facecolor="darkseagreen") data = [[5,25,50,20], [4,23,51,17], [6,22,52,19]] X = np.arange(4) plt.bar(X, data[0], color='darkorange', width=0.25, label="A") plt.bar(X, data[1], color="steelblue",  width=0.25, label="B", bottom=data[0]) plt.bar(X, data[2], color="violet",     width=0.25, label="C", bottom=np.array(data[0] + np.array(data[1]))) ax.set_title('Figure 1') plt.legend()

 

分析:

  • 使用plt.subplots(), 創建一個新的Figure和一組subplots集合,並返回一個含有已創建的subplot對象的NumPy數組。color=定義顏色
    • facecolor定義灰板的背景色。
    • nrows, ncols創建2維度的繪板,比如nrows=2, ncols=2,就是創建4個繪板
  • ax是<matplotlib.axes._subplots.AxesSubplot at 0x11fe72ad0>
  • ax.set_title()設置標題。

 

 

增加文字

plt.text(x, y, s, fontdict=None, withdash=False, **kwargs)

 

  • x ,y 是繪版上的位置
  • s是要增加的字符串
  • fontdict是一個字體的設置集合:
    • fontsize=12字體大小

例子:

fig, ax = plt.subplots(facecolor='teal') data = [[5,25,50,20], [4,23,51,17], [6,22,52,19]] X = np.arange(4) plt.bar(X+0.00, data[0], color = 'darkorange', width = 0.25,label = 'A') plt.bar(X+0.25, data[1], color = 'steelblue', width = 0.25) plt.bar(X+0.50, data[2], color = 'violet', width = 0.25,label = 'C') ax.set_title("Figure 2") plt.legend() W = [0.00,0.25,0.50] for i in range(3): for a, b in zip(X+W[i], data[i]): plt.text(a, b, "%.0f" % b, ha="center", va="bottom") plt.xlabel("Group") plt.ylabel("Num") plt.text(0, 48, "hello")

 

增加注釋:annotate

(無需使用函數,用窗口化的工具(可以直接拖拉設置的那種工具)更方便。)

在數據可視化的過程中,圖片中的文字經常被用來注釋圖中的一些特征。

plt.annotate()

  • 被注釋的地方xy(x, y)
  • 插入文本的地方xytext(x, y)

繪圖能表達意思即可。數據分析和數據挖掘,越簡潔越好。

 

plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號

X = np.linspace(0, 2*np.pi, 100)
Y = np.sin(X)
Y1 = np.cos(X)

plt.plot(X, Y)
plt.annotate("Points", xy=(1, np.sin(1)), xytext=(2, 0.4), fontsize=16, arrowprops = dict(arrowstyle="->"))
plt.title("一副測試圖")

 

 

subplots

#調整繪畫板大小

pylab.rcParams["figure.figsize"]= (x,y) 

 

matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

官方文檔有很多案例。

例子:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab

plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號

pylab.rcParams['figure.figsize'] = (10, 6)  #調整大小

np.random.seed(156948)
n_bins = 10
x = np.random.randn(1000,3)

fig, axes = plt.subplots(nrows=2, ncols=2,facecolor='darkslategray') 
#axes 是一個2維的數組。
ax0, ax1, ax2, ax3 = axes.flatten()  #flatten()變一維,並賦值。

colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')

ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)
ax1.set_title('stacked bar')

ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
ax2.set_title('stack step (unfilled)')

x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
ax3.hist(x_multi, n_bins, histtype='bar')
ax3.set_title('different sample sizes')

fig.tight_layout() #讓布局好看一點
plt.show()

 


 

 

pandas api

基礎知識(進階的需要看cookbook)

https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html

  • 各種plots的使用
  • 各種plots如何處理缺失值,以及如何自定義缺失值。
  • 一些復雜的制圖函數。各種奇形怪狀的圖
  • 繪圖格式,比如顏色,形狀大小等。
  • 直接使用matplotllib的情況,復雜的繪圖,自定義時。

 

plt.axhline(0)

增加一條水平線,在y軸0的位置。

 

df2.plot.bar(stacked=True);  stack參數設置堆疊。

bar(x, y) x默認是index, y默認是columns

 

DataFrame.hist()和pd.plot.hist()區別

前者創建多個subplots, 后者只創建一個plot。

 

hist()中by參數的用法:

根據傳入值,分組,然后形成直方圖。例子:

//1000個隨機正態分布的數字。 data = pd.Series(np.random.randn(1000)) //by參數得到一個array, 里面的元素,是整數0~3,共計1000個數字,對應data中的數字,因此被分成0~3四個組,最后形成4個圖 data.hist(by=np.random.randint(0,4, 1000))

 

 

 

 

備注:基礎沒有看完,看到Area plot

 

 




 

Seaborn統計數據可視化

基於matplotlib和pandas的數據可視化庫。 

提供高級交互操作來繪畫統計圖形

import seaborn as sns 

 

sns.set

sns.set(
    context='notebook',
    style='darkgrid',       #whitegrid, dark, white, ticks
    palette='deep',
    font='sans-serif',
    font_scale=1,
    color_codes=True,
    rc=None,
)

 

一步設置,各種美化參數。它使用了 matplotlib rcParam system,對所有的plots外觀生效,所以不使用sns,也會生效。

有多種主題,也可以自己寫:several other options,

 

sns.load_dataset(name)

  • cache=True參數默認把數據下載到本地緩存

這個函數的參數name對應官網數據庫的數據,執行函數后直接從官網下載樣本數據集合到本地。

主要目的是為了seaborn提供數據支持,無需再花費時間來加載整理數據。

例如:https://github.com/mwaskom/seaborn-data/blob/master/iris.csv

tips = sns.load_dataset("tips")
iris = sns.load_dataset("iris")

或者使用pandas.read_csv()加載數據。 

 

relplot()   

⚠️figure-level函數

figure層的接口。函數提供通道來使用不同的axes層函數。用於處理2個變量的關系relationship。 kind參數選擇使用axes層函數:

  • 默認"scatter": func:`scatterplot` (with ``kind="scatter"``; the default)
  • "line": func:`lineplot` (with ``kind="line"`` 

可選參數,這3個參數對分組數據產生不同的視覺效果:

  • hue 決定點圖的顏色,
  • size 根據數據大小,表示點圖的大小。
  • style 用不同符號表示數據點圖,  

可選參數, row, col:

使用分類變量(categorical variable),會絕對平面網格的布局。

比如col="align",align列有2個值(dots, sacc),因此會繪制3張圖。

categorical variable分類變量是一種可以采用有限數量(通常為固定數量)之一的變量,可以根據某些定性屬性將每個觀察單位或其他觀察單位分配給特定組或名義類別。

例子:

sns.relplot(x="total_bill", y="tip", col="time",
            hue="smoker", style="smoker", size="size",
            data=tips);

 

 

 

distplot()

 

jointplot() 聯合繪圖

⚠️figure-level函數, jointplot()把多個繪圖整合。

繪制出雙變量的分析圖,用於雙變量分析和單變量分析,bivariate analysis是定量分析的最簡單形式之一。

它涉及對兩個變量的分析,目的是確定它們之間的經驗關系。雙變量分析有助於檢驗簡單的關聯假設。(wiki)

 

這個函數提供了 類JointGrid的接口,和一些plot kind。這是輕量化的包裹器。如果希望使用更多的功能,直接使用JointGrid類。

參數

  • kind : { "scatter" | "reg" | "resid" | "kde" | "hex" }, 默認是scatter。

例子,可以文檔的案例,這里舉kind="reg"

sns.jointplot("total_bill", "tip", data=tips, kind="reg")

 

  • 除了基本的散點圖scatter
  • 增加了:line regression一元線性回歸。(表示'total_bill'和'tip'兩個變量之間的依賴關系。)
  • 增加了:kernel density fit.在數據上固定核密度模型(概率論中,估計未知的密度函數。)

 

Seaborn.pairplot()

⚠️figure-level函數.

智能分對兒。把一個數據集合中的變量,兩兩分隊兒,畫出所有分對兒的關系圖。

參數:

  • hue=None, 顏色分類,根據不同數值賦予不同顏色。

 


 

 

Plotting with categorical data

分類的數據的繪制。

Standard scatter and line plots visualize relationships between numerical variables, but many data analyses involve categorical variables.

標准散點和線性圖可視化了可秤量變量之間的關系,但是一些數據分析涉及到分類變量。

numerical variables:可秤量的變量,比如降雨量,心跳速率,每小時的漢堡售出數量,都是可秤量變量。

 

Seaborn提供了對這種類型數據集的優化的plot工具, catplot()

 

catplot()

一個描述可秤量變量和一個(多個)分類變量之間關系的api。

參數kind:

Categorical scatterplots:
- :func:`stripplot` (with ``kind="strip"``; 默認的✔️)
- :func:`swarmplot` (with ``kind="swarm"``) ,和strip的區別是point之間不重疊。

Categorical distribution plots:
- :func:`boxplot` (with ``kind="box"``)
- :func:`violinplot` (with ``kind="violin"``)       用kernel density estimation來表現點的樣本分布
- :func:`boxenplot` (with ``kind="boxen"``)

Categorical estimate plots:
- :func:`pointplot` (with ``kind="point"``)
- :func:`barplot` (with ``kind="bar"``)          在每個分類中顯示均值和置信區間
- :func:`countplot` (with ``kind="count"``)

 

stripplot(x,y, hue, data, jitter=True,...)  帶狀條形圖 

Draw a scatterplot where one variable is categorical.如果其中一個變量是分類的,可以使用stripplot畫散點圖。

  • jitter=True,默認,把數據分散成散點圖模式。當points是分散的時候,可以看到分布
  • hue 用不同色調區分不同類型的數據。

例子:

tips.columns
//Index(['total_bill', 'tip', 'sex', 'smoker', 'day', 'time', 'size'], dtype='object')
sns.stripplot(x='day', y ="total_bill", data=tips, hue="smoker")

 

barplot()

Show point estimates and confidence intervals as rectangular bars.顯示點的估值和置信區間,圖形是長方形條。

bar plot代表了一個關於某一數值變量的集中趨勢(均值)的估計。並且用error bars提供了一些關於估值的非確定標示。

⚠️a bar plot默認使用mean value. 通過estimator參數,可以設置中位數np.median。

confidence intervals置信區間 (生動的解釋)

  


 

 

Statistical estimation and error bars

一些函數自動的估計統計量(wiki)

估計統計量是一種數據分析框架,結合使用效應值effect size,置信區間confidence intervals,精確計划和元分析來計划實驗,分析數據並解釋結果。

  

當估計統計量發生時,seaborn會計算置信區間並畫出error bars, 用來表示非確定的估算。

seaborn的Statistical estimation超出了描述統計的范圍。比如,它使用lmplot()強化了散點圖->加上了linear regression model 

 

lmplot()

使用lmplot()可以把把線性關系可視化。

Plot data and regression model fits across a FacetGrid. 在平面網格上繪制數據和回歸模型。

默認用線性回歸: linear regression。

這個函數聯合了regplot函數和FaceGrid類。

使用implot函數可以很方便的:通過一個數據集合的置信子集來固定回歸模型。

sns.lmplot(x="total_bill", y="tip", data=tips)  ## 賬單越貴,小費越多。

參數:

  • ci=95, 默認, 即95%的置信區間。范圍是0~100
  • scatter=True, 默認使用散點圖
  • scatter_kws={"s": 80} 設置散點圖的參數。
  • order參數,If ``order`` is greater than 1, use ``numpy.polyfit`` to estimate a  polynomial regression.  多項式回歸(作出曲線)。
  • robust=True參數,去掉離群點異常值,不算入樣本分析。

 

涉及到的數理統計概念:

回歸分析,線性回歸 , 最小二乘法。簡單回歸,多項式回歸。

 


 

 

Figure-level and axes-level functions

relplot和catplot都是figure層的。

他們都會聯合使用一種特別的axes-level函數和FaceGrid對象

scatterplot(), barplot()都是axes-level函數。這是因為他們是在單獨的matplotlib axes上繪制的,並且不影響其他figure。

 

區別:

  • figure-level函數需要控制figure
  • axes-level會放到一個matplotlib figure內,它的周邊的plot可以是用seaborn制造的,也可能不是。

例子:

# 通過matplotlib繪制2個展板,並使用seaborn在展板上繪圖
import matplotlib.pyplot as plt
f, axes = plt.subplots(1, 2, sharey=True, figsize=(6, 4))
sns.boxplot(x="day", y="tip", data=tips, ax=axes[0])
sns.scatterplot(x="total_bill", y="tip", hue="day", data=tips, ax=axes[1]);

 

 

展板大小設置

figure-level函數使用height和aspect(ratio of width to height)來設置每個子展板facet。

比如設置height=4.5, 然后設置aspect=2/3,即寬是高的2/3。

例子:

sns.relplot(x="time", y="firing_rate", col="align",
           hue="choice", size="coherence", style="choice",
           height=4.5, aspect=2/3,
           facet_kws=dict(sharex=False),
           kind="line", legend="full", data=dots);

 

 

客制化圖表的外觀:參考https://seaborn.pydata.org/introduction.html的customizing plot appearance

 

每個變量是1列,每次觀察是一行.


 

Next steps

畫廊,各種圖表樣式:https://seaborn.pydata.org/examples/index.html#example-gallery

官方tutorial:  https://seaborn.pydata.org/tutorial.html#tutorial

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM