Seaborn是一個基于matplotlib的可視化庫,其為用戶提供了高級接口,并且該工具還深度集成了pandas的數據結構。并且該工具該集成了很多數據庫,配合官網給出的代碼示例,可以更方便的進行操作。
官網對它的介紹為:
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.Seaborn is a library for making statistical graphics in Python. It builds on top of matplotlib and integrates closely with pandas data structures.Seaborn helps you explore and understand your data. Its plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots. Its dataset-oriented, declarative API lets you focus on what the different elements of your plots mean, rather than on the details of how to draw them.
官網地址為:https://seaborn.pydata.org/
提示:引入seaborn會修改matplotlib默認的顏色方案和繪圖類型,以提高可讀性和美觀度。即使不使用seaborn API,可能也會引入seaborn,作為提高美觀度和繪制常見matplotlib圖形的簡化方法。
和matplotlib一般被命令為plt一樣,seaborn一般被命名為sns. 通常采用如下的導入方式:
import seaborn as sns
示例
這里先看一個示例:
# Import seaborn
import seaborn as sns
import pandas as pd# Apply the default theme
sns.set_theme()# Load an example dataset
tips = pd.read_csv(r"tips.csv")# Create a visualization
sns.relplot(data=tips,x="total_bill", y="tip", col="time",hue="smoker", style="smoker", size="size",
)
首先在上面的代碼中,導入了seaborn、pandas兩個庫。
然后set_theme()實際則是使用matplotlib rcParam系統,并對matplotlib進行配置,從而影響到最后的顯示。不過上面使用的是默認配置。
除了默認配置之外,可以使用參數獨立控制繪圖的風格和縮放比例等。
def set_theme(context="notebook", style="darkgrid", palette="deep",font="sans-serif", font_scale=1, color_codes=True, rc=None):"""Set aspects of the visual theme for all matplotlib and seaborn plots.This function changes the global defaults for all plots using thematplotlib rcParams system. The themeing is decomposed into several distinctsets of parameter values.The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`and :doc:`color palette <../tutorial/color_palettes>` tutorials.Parameters----------context : string or dictScaling parameters, see :func:`plotting_context`.style : string or dictAxes style parameters, see :func:`axes_style`.palette : string or sequenceColor palette, see :func:`color_palette`.font : stringFont family, see matplotlib font manager.font_scale : float, optionalSeparate scaling factor to independently scale the size of thefont elements.color_codes : boolIf ``True`` and ``palette`` is a seaborn palette, remap the shorthandcolor codes (e.g. "b", "g", "r", etc.) to the colors from this palette.rc : dict or NoneDictionary of rc parameter mappings to override the above.Examples--------.. include:: ../docstrings/set_theme.rst"""set_context(context, font_scale)set_style(style, rc={"font.family": font})set_palette(palette, color_codes=color_codes)if rc is not None:mpl.rcParams.update(rc)
這里和官網的示例有差異,是直接將csv文件下載到本地利用pd.read_csv()方法導入的。
之前提到seaborn和pandas關系緊密,因此能夠直接使用pandas中的數據結構。
最后是使用relplot()函數創建的圖表。
和matplotlib不同,seaborn的圖表函數中,data參數是必須的,該參數指定了數據集,seaborn能夠從該參數中推斷要顯示的數據。其他參數都是可選的,并且不需要指定圖表元素的屬性,比如顏色和標記。
數據結構
關于數據結構,使用seaborn最好是使用pandas DataFrame或者numpy array。
雖然list也可以直接使用,但是直接使用list不能發揮seaborn的優勢,有點大材小用了。
data = [5,7,6,2,6,8,6,2,4,9]sns.relplot(data, kind="line")
參數
這里看一下常用的幾個參數:
- data:表示要使用的數據集。可以是 Pandas DataFrame、NumPy 數組或其他數據結構。
- x、y:表示要繪制的數據的變量。在大多數函數中,x 和 y 分別表示橫軸和縱軸上的數據變量。
- col:用于指定分組圖表中的列變量。當需要根據數據的某個特定變量進行分組并繪制多個子圖時,可以使用 col 參數。
- hue:表示要對數據進行分組的變量,可以通過顏色或其他視覺屬性來區分不同的組。
- palette:表示要使用的顏色調色板。可以是預定義的調色板名稱,也可以是自定義的顏色列表。
- size、sizes:表示散點圖中數據點的大小。size 參數控制所有數據點的大小,而 sizes 參數可以傳入一個數組或列表,用于指定每個數據點的大小。
- -style:表示散點圖中數據點的樣式。可以是預定義的樣式名稱,也可以是一個數組或列表,用于為每個數據點指定樣式。
- kind:用于指定要創建的圖表類型
- alpha:表示圖表元素的透明度。可以是一個介于 0 和 1 之間的浮點數。
- linewidth、edgecolor:表示線條的寬度和顏色。
- bins:表示直方圖中的條形數或箱線圖中箱子的數量。
- orient:表示條形圖的方向,可以是 'v'(垂直)或 'h'(水平)。
- ax:用于指定要在其上繪制圖表的matplotlib Axes對象
上圖總結起來就是:
- 源數據為tips
- x軸數據為tips中的total_bill列,y軸數據為tips中的tip列
- 利用time列中的數據進行分組,time列中存在兩類數據,分別為Lunch和Dinner,所以分為兩個圖
- hue參數為smoker列,smoker列中存在兩類數據,分別為Yes和No,所以每個圖中又分為兩類,即每個圖中的數據按照Yes和No分為兩類
- style參數為smoker列,smoker列中存在兩類數據,分別為Yes和No,這里用顏色區分,顏色為默認設置中的配置
- size參數為size列,size列中存在6類,在圖中就是數據點的大小不同
而kind參數主要有以下幾種:
- kind='line':折線圖(Line plot)
- kind='scatter':散點圖(Scatter plot)
- kind='bar':條形圖(Bar plot)
- kind='barh':水平條形圖(Horizontal bar plot)
- kind='hist':直方圖(Histogram)
- kind='box':箱線圖(Box plot)
- kind='violin':小提琴圖(Violin plot)
- kind='pie':餅圖(Pie chart)
- kind='heatmap':熱力圖(Heatmap)
- kind='kde':核密度估計圖(Kernel density plot)
- kind='reg':線性回歸圖(Linear regression plot)
其它的參數也都有設置值,可查看官網或相關文檔。
圖表類型
從上面可以看出使用seaborn和matplotlib的區別,seaborn更加簡潔,但是matplotlib更加靈活。
使用seaborn不用考慮圖表的格式,線型,顏色,字體等等,只需要關注數據的分析。
而seaborn中主要的圖表類型有三大類,分別是:
- 關系圖
- 分布圖
- 分類圖
其中關系圖的接口為relplot(),它是一個Figure-level的函數。
在關系圖中,可以使用kind參數來指定關系圖的類型,例如散點圖(scatter plot)、折線圖(line plot)等。
另外也可以直接使用對應的接口做出對應的圖形,比如:
- relplot():創建關系圖的通用函數,可以繪制散點圖、折線圖、小提琴圖等不同類型的圖表。
- scatterplot():繪制散點圖,用于顯示兩個連續變量之間的關系。
- lineplot():繪制折線圖,用于顯示一個連續變量隨另一個連續變量的變化趨勢。
將上面的rellplot()函數改為scatterplot()函數,一樣可以得到相同的結果,只是從美觀的角度來看,沒有relplot()的結果好看
import matplotlib.pyplot as pltf, axs = plt.subplots(1, 2)sns.scatterplot(data=tips[tips["time"] == "Dinner"], x="total_bill", y="tip", hue="smoker", style="smoker", size="size", ax=axs[0])
sns.scatterplot(data=tips[tips["time"] == "Lunch"], x="total_bill", y="tip", hue="smoker", style="smoker", size="size", ax=axs[1])f.tight_layout()
分布圖的接口為displot(),它也是一個Figure-level的函數。
在分布圖中,可以使用kind參數來指定分布圖的類型,例如直方圖(hist plot)、核密度估計圖(kde plot)、累積分布圖(ecdf plot)等。
另外也可以直接使用對應的接口做出對應的圖形,比如:
- displot():繪制直方圖、核密度估計圖和經驗累積分布函數等不同類型的單變量分布圖。
- histplot():繪制直方圖,用于顯示單變量的分布。
- kdeplot():繪制核密度估計圖,用于顯示單變量的概率密度估計。
- ecdfplot():繪制經驗累積分布函數圖,用于顯示單變量的經驗累積分布。
- rugplot():繪制地毯圖,用于顯示單變量的數據點分布。
分類圖的接口為catplot(),它也是一個Figure-level的函數。
在分類圖中,可以使用kind參數來指定分布圖的類型,例如條形圖(bar plot)、箱線圖(box plot)、小提琴圖(violin plot)等。
另外也可以直接使用對應的接口做出對應的圖形,比如:
- barplot():繪制條形圖,用于顯示分類變量和數值變量之間的關系。
- pointplot():繪制點圖,用于顯示分類變量和數值變量之間的關系,并顯示置信區間。
- boxplot():繪制箱線圖,用于顯示分類變量和數值變量之間的關系,并顯示分位數和異常值。
- violinplot():繪制小提琴圖,用于顯示分類變量和數值變量之間的關系,并顯示分布和概率密度。
- stripplot():繪制散點圖,用于顯示分類變量和數值變量之間的關系。
- swarmplot():繪制蜂群圖,用于顯示分類變量和數值變量之間的關系,并在同一位置上顯示每個數據點。
其實可以將seaborn的圖像看成是matplotlib的圖像,只是在matplotlib的基礎上進行了美化,使用戶可以關注于數據分析本身,而不是圖像的細節控制。
圖像的保存
既然seaborn的圖像是matplotlib的圖像,那么就可以使用matplotlib的保存方法來保存seaborn的圖像。
plt.savefig("test.png")