天天看點

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

seaborn官方文檔:http://seaborn.pydata.org/api.html

繪制多變量的分布圖

  先繪制兩個變量的分布圖,其中X變量為分類變量,Y為數值變量。

1 import pandas as pd
2 import numpy as np
3 import seaborn as sns
4 import matplotlib.pyplot as plt
5 import matplotlib as mpl
6 tips = sns.load_dataset("tips")
7 sns.set(style="whitegrid", color_codes=True)
8 sns.stripplot(x="day", y="total_bill", data=tips)
9 plt.show()      

  運作結果:

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  注意:觀察上圖不難發現,帶圖預設是有抖動的,即 jitter=True 。下面用 swarmplot 繪制帶分布的散點圖。并且将展示在圖中分割多個分類變量,以不同的顔色展示。

1 plt.subplot(121)
2 sns.swarmplot(x="day", y="total_bill", data=tips)
3 plt.subplot(122)
4 sns.swarmplot(x="day", y="total_bill", hue="sex", data=tips)
5 plt.show()
6 sns.swarmplot(x="total_bill", y="day", hue="time", data=tips)
7 plt.show()      

  運作結果:

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  通過上面的圖像我們很容易觀察到 day 與 time 、sex 之間的一些關系。

 箱線圖與小提琴圖

   下面我們将繪制箱線圖以及小提琴圖展示 變量間的關系

 盒圖

  IQR即統計學概念四分位距,第一/四分位 與 第三/四分位之間的距離

  N = 1.5IQR 如果一個值>Q3+N或 < Q1-N,則為離群點

1 sns.boxplot(x="day", y="total_bill", hue="time", data=tips)
2 plt.show()      

  運作結果:

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  小提琴圖可以做類似的效果,且能夠展示其分布

1 sns.violinplot(x="total_bill", y="day", hue="time", data=tips)
2 plt.show()      

  運作結果:

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  中間的黑色粗線為4分位距,細線為 95% 置信區間。我們也可以将小提琴圖設定為一邊顯示一個類别,這樣對比性就更加明确。

1 sns.violinplot(x="day", y="total_bill", hue="sex", data=tips)
2 plt.show()
3 sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True)
4 plt.show()      

  運作結果:

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  明顯可以發現上面第二張圖區分更明顯。兩種函數結合可以生成更加炫酷的圖:

1 sns.violinplot(x="day", y="total_bill", data=tips, inner=None)  # inner 小提琴内部圖形
2 sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5)  # alpha 透明度
3 plt.show()
4 sns.violinplot(x="day", y="total_bill", data=tips, inner=None)
5 sns.swarmplot(x="day", y="total_bill", data=tips, color="w",)
6 plt.show()      
Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  當然我們也可以橫着展示箱線圖:

1 sns.boxplot(data=iris, orient="h")  # orient  垂直和水準
2 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

條形圖

  顯示圖的集中趨勢

1 titanic = sns.load_dataset("titanic")
2 print(titanic.describe())
3 print(titanic.info())
4 sns.barplot(x="sex", y="survived", hue="class", data=titanic)
5 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

點圖可以更好的描述變化差異

   對class屬性分類繪制:

1 sns.pointplot(x="sex", y="survived", hue="class", data=titanic)
2 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  改變線形和點的形狀

1 sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
2               palette={"male": "g", "female": "m"},
3               markers=["^", "o"], linestyles=["-", "--"])
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

 多層面闆分類圖

  下面展示的是 catplot 函數,及其參數說明:

# catplot(x=None, y=None, hue=None, data=None, row=None, col=None,
#             col_wrap=None, estimator=np.mean, ci=95, n_boot=1000,
#             units=None, order=None, hue_order=None, row_order=None,
#             col_order=None, kind="strip", height=5, aspect=1,
#             orient=None, color=None, palette=None,
#             legend=True, legend_out=True, sharex=True, sharey=True,
#             margin_titles=False, facet_kws=None, **kwargs)      
Parameters: x, y, hue : names of variables in 

data

Inputs for plotting long-form data. See examples for interpretation.
data : DataFrame
Long-form (tidy) dataset for plotting. Each column should correspond to a variable, and each row should correspond to an observation.
row, col : names of variables in 

data

, optional
Categorical variables that will determine the faceting of the grid.
col_wrap : int, optional
“Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a 

row

 facet.
estimator : callable that maps vector -> scalar, optional
Statistical function to estimate within each categorical bin.
ci : float or “sd” or None, optional
Size of confidence intervals to draw around estimated values. If “sd”, skip bootstrapping and draw the standard deviation of the observations. If 

None

, no bootstrapping will be performed, and error bars will not be drawn.
n_boot : int, optional
Number of bootstrap iterations to use when computing confidence intervals.
units : name of variable in 

data

 or vector data, optional
Identifier of sampling units, which will be used to perform a multilevel bootstrap and account for repeated measures design.
order, hue_order : lists of strings, optional
Order to plot the categorical levels in, otherwise the levels are inferred from the data objects.
row_order, col_order : lists of strings, optional
Order to organize the rows and/or columns of the grid in, otherwise the orders are inferred from the data objects.
kind : string, optional
The kind of plot to draw (corresponds to the name of a categorical plotting function. Options are: “point”, “bar”, “strip”, “swarm”, “box”, “violin”, or “boxen”.
height : scalar, optional
Height (in inches) of each facet. See also: 

aspect

.
aspect : scalar, optional
Aspect ratio of each facet, so that 

aspect * height

 gives the width of each facet in inches.
orient : “v” | “h”, optional
Orientation of the plot (vertical or horizontal). This is usually inferred from the dtype of the input variables, but can be used to specify when the “categorical” variable is a numeric or when plotting wide-form data.
color : matplotlib color, optional
Color for all of the elements, or seed for a gradient palette.
palette : palette name, list, or dict, optional
Colors to use for the different levels of the 

hue

 variable. Should be something that can be interpreted by 

color_palette()

, or a dictionary mapping hue levels to matplotlib colors.
legend : bool, optional
If 

True

 and there is a 

hue

 variable, draw a legend on the plot.
legend_out : bool, optional
If 

True

, the figure size will be extended, and the legend will be drawn outside the plot on the center right.
share{x,y} : bool, ‘col’, or ‘row’ optional
If true, the facets will share y axes across columns and/or x axes across rows.
margin_titles : bool, optional
If 

True

, the titles for the row variable are drawn to the right of the last column. This option is experimental and may not work in all cases.
facet_kws : dict, optional
Dictionary of other keyword arguments to pass to 

FacetGrid

.
kwargs : key, value pairings
Other keyword arguments are passed through to the underlying plotting function.
Returns: g : 

FacetGrid

Returns the 

FacetGrid

 object with the plot on it for further tweaking.

  Parameters:

  x,y,hue 資料集變量 變量名

  date 資料集 資料集名

  row,col 更多分類變量進行平鋪顯示 變量名

  col_wrap 每行的最高平鋪數 整數

  estimator 在每個分類中進行矢量到标量的映射 矢量

  ci 置信區間 浮點數或None

  n_boot 計算置信區間時使用的引導疊代次數 整數

  units 采樣單元的辨別符,用于執行多級引導和重複測量設計 資料變量或向量資料

  order, hue_order 對應排序清單 字元串清單

  row_order, col_order 對應排序清單 字元串清單

  kind : 可選:point 預設, bar 柱形圖, count 頻次, box 箱體, violin 提琴, strip 散點,swarm 分散點

  size 每個面的高度(英寸) 标量  已經不用了,現在使用height

  aspect 縱橫比 标量

  orient 方向 "v"/"h"

  color 顔色 matplotlib顔色

  palette 調色闆名稱 seaborn顔色色闆

  legend_hue  布爾值:如果是真的,圖形大小将被擴充,并且圖畫将繪制在中心右側的圖外。

  share{x,y} 共享軸線 True/False:如果為真,則刻面将通過列和/或X軸在行之間共享Y軸。

   下面将是常用圖像的展示:

1 sns.catplot(x="day", y="total_bill", hue="smoker", data=tips)
2 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 sns.catplot(x="day", y="total_bill", hue="smoker", data=tips, kind="bar")
2 plt.show()      

   

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 sns.catplot(x="day", y="total_bill", hue="smoker",
2             col="time", data=tips, kind="swarm")
3 plt.show()      

   

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 sns.catplot(x="time", y="total_bill", hue="smoker",
2             col="day", data=tips, kind="box", height=4, aspect=.5)
3 plt.show()      

   

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

 用 FacetGrid 這個類來展示資料

  更多内容請點選上面的連結,下面将簡單展示

1 g = sns.FacetGrid(tips, col="time")                    # 占位
2 g.map(plt.hist, "tip")                                 # 畫圖;第一個參數是func
3 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 g = sns.FacetGrid(tips, col="sex", hue="smoker")
2 g.map(plt.scatter, "total_bill", "tip", alpha=.7)
3 g.add_legend()
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 sns.set_style("ticks")
2 g = sns.FacetGrid(tips, row="smoker", col="time", margin_titles=True)  # 變量标題右側,實驗性并不總是有效
3 g.map(sns.regplot, "size", "total_bill", color=".1", fit_reg=False, x_jitter=.1)  # color 顔色深淺  fit_reg  回歸的線  x_jitter 浮動
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 g = sns.FacetGrid(tips, col="day", height=4, aspect=.5)
2 g.map(sns.barplot, "sex", "total_bill", order=["Male", "Female"])
3 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 from pandas import Categorical
2 ordered_days = tips.day.value_counts().index
3 print(ordered_days)
4 ordered_days = Categorical(['Thur', 'Fri', 'Sat', 'Sun'])
5 g = sns.FacetGrid(tips, row="day", row_order=ordered_days,
6                   height=1.7, aspect=4)
7 g.map(sns.boxplot, "total_bill", order=["Male","Female"])
8 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 pal = dict(Lunch="seagreen", Dinner="gray")
2 g = sns.FacetGrid(tips, hue="time", palette=pal, height=5)
3 g.map(plt.scatter, "total_bill", "tip", s=50, alpha=.7, linewidth=.5, edgecolors="red") # edgecolors 元素邊界顔色
4 g.add_legend()
5 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 g = sns.FacetGrid(tips, hue="sex", palette="Set1", height=5, hue_kws={"marker": ["^", "v"]})
2 g.map(plt.scatter, "total_bill", "tip", s=100, linewidth=.5, edgecolor="white")
3 g.add_legend()
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 with sns.axes_style("white"):
2     g = sns.FacetGrid(tips, row="sex", col="smoker", margin_titles=True, height=2.5)
3 g.map(plt.scatter, "total_bill", "tip", color="#334488", edgecolor="white", lw=.5)
4 g.set_axis_labels("Total bill (US Dollars)", "Tip")
5 g.set(xticks=[10, 30, 50], yticks=[2, 6, 10])
6 g.fig.subplots_adjust(wspace=.02, hspace=.02)  # 子圖與子圖
7 # g.fig.subplots_adjust(left  = 0.125,right = 0.5,bottom = 0.1,top = 0.9, wspace=.02, hspace=.02)
8 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

PairGrid 的簡單展示      
1 iris = sns.load_dataset("iris")
2 g = sns.PairGrid(iris)
3 g.map(plt.scatter)
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 g = sns.PairGrid(iris)
2 g.map_diag(plt.hist)        # 對角線
3 g.map_offdiag(plt.scatter)  # 非對角線
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 g = sns.PairGrid(iris, hue="species")
2 g.map_diag(plt.hist)
3 g.map_offdiag(plt.scatter)
4 g.add_legend()
5 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 g = sns.PairGrid(iris, vars=["sepal_length", "sepal_width"], hue="species")  # vars 取一部分
2 g.map(plt.scatter)
3 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 g = sns.PairGrid(tips, hue="size", palette="GnBu_d")
2 g.map(plt.scatter, s=50, edgecolor="white")
3 g.add_legend()
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

熱力圖

   用顔色的深淺、亮度等來顯示資料的分布

1 uniform_data = np.random.rand(3, 3)
2 print(uniform_data)
3 heatmap = sns.heatmap(uniform_data)
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 ax = sns.heatmap(uniform_data, vmin=0.2, vmax=0.5)  # 最大最小取值
2 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  注意上圖的随機數發生了變化。

1 normal_data = np.random.randn(3, 3)
2 print(normal_data)
3 ax = sns.heatmap(normal_data, center=0)      # 中心值
4 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 flights = sns.load_dataset("flights")
2 print(flights.head())
3 flights = flights.pivot("month", "year", "passengers")  # 根據列值重塑資料
4 print(flights)
5 sns.heatmap(flights)
6 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 # fmt參數在這裡是必須的,不然會亂碼
2 sns.heatmap(flights, annot=True, fmt="d")
3 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 sns.heatmap(flights, linewidths=.4)
2 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 sns.heatmap(flights, cmap="YlGnBu")  # 指定資料值到顔色空間的映射;如果不提供,預設将取決于是否設定了中心
2 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...
1 sns.heatmap(flights, cbar=False)  # 隐藏bar
2 plt.show()      

  

Python資料可視化庫seaborn ------ 多變量的分布繪圖:stripplot()、swarmplot();箱線圖與小提琴圖;條形圖;點圖;多層面闆分類圖:catplot函數、FacetG...

轉載于:https://www.cnblogs.com/dan-baishucaizi/p/9474387.html