python机器学习-Python Seaborn
本文是Python 机器学习系列的一部分。您可以在此处找到本系列之前所有帖子的链接
介绍
在上一章中,我们研究了 Python MatPlotLib、它的函数和它的 Python 实现。
在本章中,我们将从下一个非常有用且重要的 Python 机器学习库“Python Seaborn”开始。
什么是 Python Seaborn?
Seaborn 是一个用 Python 制作统计图形的库。它建立在 matplotlib 之上,并与 Pandas 数据结构紧密集成。
以下是 seaborn 提供的一些功能:
- 用于检查多个变量之间关系的面向数据集的 API
- 专门支持使用分类变量来显示观察或聚合统计数据
- 用于可视化单变量或双变量分布以及在数据子集之间比较它们的选项
- 自动估计和绘制不同类型因变量的线性回归模型
- 方便地查看复杂数据集的整体结构
- 用于构建多图网格的高级抽象,可让您轻松构建复杂的可视化
- 使用多个内置主题对 matplotlib 图形样式进行简洁控制
- 用于选择可忠实显示数据模式的调色板的工具
Seaborn 旨在使可视化成为探索和理解数据的核心部分。其面向数据集的绘图功能对包含整个数据集的数据框和数组进行操作,并在内部执行必要的语义映射和统计聚合以生成信息图
官网是seaborn.pydata.org
安装 Seaborn
1. Ubuntu/Linux
sudo apt update -y
sudo apt upgrade -y
sudo apt install python3-tk python3-pip -y
sudo pip install seaborn -y
2. Anaconda Prompt
conda install -c anaconda seaborn
Matplotlib 和 Seaborn 的区别
绘图库 | Seaborn | |
功能 | Matplotlib 主要用于基本绘图。使用 Matplotlib 的可视化通常由条形图、饼图、线条、散点图等组成。 | 另一方面,Seaborn 提供了多种可视化模式。它使用较少的语法并具有很有趣的默认主题。它专门用于统计可视化,如果必须在可视化中汇总数据并显示数据中的分布,就会使用它。 |
处理多个数字 | Matplotlib 有多个图形可以打开,但需要显式关闭。plt.close() 仅关闭当前图形。plt.close(‘all’) 将全部关闭。 | Seaborn 可以自动创建多个图形。这有时会导致 OOM(内存不足)问题。 |
可视化 | Matplotlib 是 Python 中用于数据可视化的图形包。它与 NumPy 和 Pandas 很好地集成在一起。pyplot 模块密切反映了 MATLAB 绘图命令。因此,MATLAB 用户可以轻松过渡到使用 Python 绘图。 | Seaborn 在处理 Pandas 数据帧方面更加集成。它扩展了 Matplotlib 库,以使用一组更直接的方法使用 Python 创建漂亮的图形。 |
数据帧和数组 | Matplotlib 处理数据框和数组。它具有用于绘图的不同状态 API。数字和 ace 由对象表示,因此无需管理参数即可调用 plot() 之类的没有参数的调用。 | Seaborn 将数据集作为一个整体处理,并且比 Matplotlib 直观得多。对于 Seaborn,replot() 是带有“kind”参数的入口 API,用于指定绘图类型,可以是线、条或任何其他类型。Seaborn 不是有状态的。因此, plot() 将需要传递对象。 |
灵活性 | Matplotlib 是高度可定制且功能强大的。 | Seaborn 通过提供常用的默认主题来避免大量样板文件。 |
用例 |
Pandas 使用 Matplotlib。它是一个围绕 Matplotlib 的简洁包装器。
|
Seaborn 适用于更具体的用例。此外,它是引擎盖下的 Matplotlib。它专门用于统计绘图。 |
Seaborn 函数
1. seaborn.relplot()
seaborn.relplot(x=None, y=None, hue=None, size=None, style=None, data=None, row=None, col=None, col_wrap=None, row_order=None, col_order=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, markers=None, dashes=None, style_order=None, legend=’brief’, kind=’scatter’, height=5, aspect=1, facet_kws=None, **kwargs)
它是一个图形级接口的函数,用于在 FacetGrid 上绘制关系图。
import seaborn as sns
sns.set(style="white")
# Load the example mpg dataset
mpg = sns.load_dataset("mpg")
# Plot miles per gallon against horsepower with other semantics
sns.relplot(x="horsepower", y="mpg", hue="origin", size="weight",
sizes=(400, 40), alpha=.5, palette="muted",
height=6, data=mpg)
输出
2. seaborn.scatterplot()
句法
seaborn.scatterplot(x=None, y=None, hue=None, style=None, size=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, markers=True, style_order=None, x_bins=None, y_bins=None, units=None, estimator=None, ci=95, n_boot=1000, alpha=’auto’, x_jitter=None, y_jitter=None, legend=’brief’, ax=None, **kwargs)
绘制具有多个语义分组可能性的散点图。
import seaborn as sns
sns.set()
# Load the example iris dataset
planets = sns.load_dataset("planets")
cmap = sns.cubehelix_palette(rot=-.5, as_cmap=True)
ax = sns.scatterplot(x="distance", y="orbital_period",
hue="year", size="mass",
palette=cmap, sizes=(100, 100),
data=planets)
输出
3. seaborn.lineplot()
句法
seaborn.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs)
绘制具有多个语义分组可能性的线图。
import numpy as np
import pandas as pd
import seaborn as sns
sns.set(style="whitegrid")
rs = np.random.RandomState(365)
values = rs.randn(365, 4).cumsum(axis=0)
dates = pd.date_range("1 1 2016", periods=365, freq="D")
data = pd.DataFrame(values, dates, columns=["A", "B", "C", "D"])
data = data.rolling(10).mean()
sns.lineplot(data=data, palette="tab10", linewidth=2.5)
输出
4. seaborn.catplot()
句法
seaborn.catplot(x=None, y=None, hue=None, data=None, row=None, col=None, col_wrap=None, estimator=<function 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)
用于在 FacetGrid 上绘制分类图的图形级界面。
import seaborn as sns
sns.set(style="whitegrid")
# Load the example exercise dataset
df = sns.load_dataset("exercise")
# Draw a pointplot to show pulse as a function of three categorical factors
g = sns.catplot(x="pulse", y="time", hue="diet", col="kind",
capsize=.6, palette="YlGnBu_d", height=6, aspect=.75,
kind="point", data=df)
g.despine(left=True)
输出
5. seaborn.stripplot()
句法
seaborn.stripplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, jitter=True, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor=’gray’, linewidth=0, ax=None, **kwargs)
绘制一个散点图,其中一个变量是分类变量。
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
iris = sns.load_dataset("iris")
# "Melt" the dataset to "long-form" or "tidy" representation
iris = pd.melt(iris, "species", var_name="measurement")
# Initialize the figure
f, ax = plt.subplots()
sns.despine(bottom=True, left=True)
# Show each observation with a scatterplot
sns.stripplot(x="measurement", y="value", hue="species",
data=iris, dodge=True, jitter=True,
alpha=.25, zorder=1)
# Show the conditional means
sns.pointplot(x="measurement", y="value", hue="species",
data=iris, dodge=.532, join=False, palette="dark",
markers="d", scale=.75, ci=None)
# Improve the legend
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[3:], labels[3:], title="species",
handletextpad=0, columnspacing=1,
loc="lower right", ncol=3, frameon=True)
输出
6. seaborn.swarmplot()
句法
seaborn.swarmplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor=’gray’, linewidth=0, ax=None, **kwargs)
绘制具有非重叠点的分类散点图。
import pandas as pd
import seaborn as sns
sns.set(style="whitegrid", palette="muted")
# Load the example iris dataset
iris = sns.load_dataset("iris")
# "Melt" the dataset to "long-form" or "tidy" representation
iris = pd.melt(iris, "species", var_name="measurement")
# Draw a categorical scatterplot to show each observation
sns.swarmplot(x="value", y="measurement", hue="species",
palette=["r", "c", "y"], data=iris)
输出
7.seaborn.boxplot()
句法
绘制箱线图以显示关于类别的分布。
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
# Initialize the figure with a logarithmic x axis
f, ax = plt.subplots(figsize=(7, 6))
ax.set_xscale("log")
# Load the example planets dataset
planets = sns.load_dataset("planets")
# Plot the orbital period with horizontal boxes
sns.boxplot(x="distance", y="method", data=planets,
whis="range", palette="vlag")
# Add in points to show each observation
sns.swarmplot(x="distance", y="method", data=planets,
size=2, color=".6", linewidth=0)
# Tweak the visual presentation
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.despine(trim=True, left=True)
输出
8. seaborn.violinplot()
句法
seaborn.violinplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, bw=’scott’, cut=2, scale=’area’, scale_hue=True, gridsize=100, width=0.8, inner=’box’, split=False, dodge=True, orient=None, linewidth=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)
绘制箱线图和核密度估计的组合。
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
# Load the example dataset of brain network correlations
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
# Pull out a specific subset of networks
used_networks = [1, 3, 4, 5, 6, 7, 8, 11, 12, 13, 16, 17]
used_columns = (df.columns.get_level_values("network")
.astype(float)
.isin(used_networks))
df = df.loc[:, used_columns]
# Compute the correlation matrix and average over networks
corr_df = df.corr().groupby(level="network").mean()
corr_df.index = corr_df.index.astype(int)
corr_df = corr_df.sort_index().T
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 6))
# Draw a violinplot with a narrower bandwidth than the default
sns.violinplot(data=corr_df, palette="Set3", bw=1, cut=.2, linewidth=1)
# Finalize the figure
ax.set(ylim=(-.7, 1.05))
sns.despine(left=True, bottom=True)
9. seaborn.boxenplot()
句法
为更大的数据集绘制增强的箱线图。
import seaborn as sns
sns.set(style="whitegrid")
diamonds = sns.load_dataset("diamonds")
clarity_ranking = ["I1", "SI2", "SI1", "VVS2", "VVS1", "IF" "VS2", "VS1"]
sns.boxenplot(x="clarity", y="carat",
color="g", order=clarity_ranking,
scale="linear", data=diamonds)
输出
10. seaborn.pointplot()
句法
使用散点图显示点估计和置信区间。
import seaborn as sns
sns.set(style="whitegrid")
# Load the example Titanic dataset
titanic = sns.load_dataset("titanic")
# Set up a grid to plot survival probability against several variables
g = sns.PairGrid(titanic, y_vars="survived",
x_vars=["class", "sex"],
height=5, aspect=.5)
# Draw a seaborn pointplot onto each Axes
g.map(sns.pointplot, scale=1.3, errwidth=4, color="xkcd:plum")
g.set(ylim=(0, 1))
sns.despine(fig=g.fig, left=True)
输出
11. seaborn.barplot()
句法
将点估计值和置信区间显示为矩形条。
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", context="talk")
rs = np.random.RandomState(8)
# Set up the matplotlib figure
f, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7, 5), sharex=True)
# Generate some sequential data
x = np.array(list("ABCDEFGHIJ"))
y1 = np.arange(1, 11)
sns.barplot(x=x, y=y1, palette="rocket", ax=ax1)
ax1.axhline(0, color="k", clip_on=False)
ax1.set_ylabel("Sequential")
# Center the data to make it diverging
y2 = y1 - 5.5
sns.barplot(x=x, y=y2, palette="vlag", ax=ax2)
ax2.axhline(0, color="k", clip_on=False)
ax2.set_ylabel("Diverging")
# Randomly reorder the data to make it qualitative
y3 = rs.choice(y1, len(y1), replace=False)
sns.barplot(x=x, y=y3, palette="deep", ax=ax3)
ax3.axhline(0, color="k", clip_on=False)
ax3.set_ylabel("Qualitative")
# Finalize the plot
sns.despine(bottom=True)
plt.setp(f.axes, yticks=[])
plt.tight_layout(h_pad=2)
输出
12. seaborn.countplot()
句法
使用条形显示每个分类 bin 中的观察计数。
import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
g = sns.catplot(x="class", hue="who", col="survived", data=titanic, kind="count", height=4, aspect=.7)
输出
13. seaborn.jointplot()
句法
用双变量和单变量图绘制两个变量的图。
import numpy as np
import seaborn as sns
sns.set(style="ticks")
rs = np.random.RandomState(11)
x = rs.gamma(1, size=500)
y = -.5 * x + rs.normal(size=500)
sns.jointplot(x, y, kind="hex", color="#4CB391")
输出
14. seaborn.pairplot()
句法
在数据集中绘制成对关系。
输出
15. seaborn.distplot()
句法
seaborn.distplot(a, bins=None, hist=True, kde=True, rug=False, fit=None, hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None, vertical=False, norm_hist=False, axlabel=None, label=None, ax=None)
灵活地绘制观察的单变量分布。
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", palette="muted", color_codes=True)
rs = np.random.RandomState(10)
# Set up the matplotlib figure
f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)
sns.despine(left=True)
# Generate a random univariate dataset
d = rs.normal(size=100)
# Plot a simple histogram with binsize determined automatically
sns.distplot(d, kde=False, color="b", ax=axes[0, 0])
# Plot a kernel density estimate and rug plot
sns.distplot(d, hist=False, rug=True, color="r", ax=axes[0, 1])
# Plot a filled kernel density estimate
sns.distplot(d, hist=False, color="g", kde_kws={"shade": True}, ax=axes[1, 0])
# Plot a historgram and kernel density estimate
sns.distplot(d, color="m", ax=axes[1, 1])
plt.setp(axes, yticks=[])
plt.tight_layout()
输出
16. seaborn.kdeplot()
句法
拟合并绘制单变量或双变量核密度估计值。
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="dark")
rs = np.random.RandomState(500)
# Set up the matplotlib figure
f, axes = plt.subplots(3, 3, figsize=(9, 9), sharex=True, sharey=True)
# Rotate the starting point around the cubehelix hue circle
for ax, s in zip(axes.flat, np.linspace(0, 3, 10)):
# Create a cubehelix colormap to use with kdeplot
cmap = sns.cubehelix_palette(start=s, light=1, as_cmap=True)
# Generate and plot a random bivariate dataset
x, y = rs.randn(2, 50)
sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=ax)
ax.set(xlim=(-3, 3), ylim=(-3, 3))
f.tight_layout()
输出
17. seaborn.rugplot()
句法
seaborn.rugplot(a, height=0.05, axis=’x’, ax=None, **kwargs)
将数组中的数据点绘制为轴上的棒。
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sample = np.hstack((np.random.randn(300), np.random.randn(200)+5))
fig, ax = plt.subplots(figsize=(8,4))
sns.distplot(sample, rug=True, hist=False, rug_kws={"color": "g"},
kde_kws={"color": "k", "lw": 3})
plt.show()
输出
18. seaborn.lmplot()
句法
绘制数据和回归模型在 FacetGrid 中拟合。
import seaborn as sns
sns.set()
# Load the iris dataset
iris = sns.load_dataset("iris")
# Plot sepal with as a function of sepal_length across days
g = sns.lmplot(x="sepal_length", y="sepal_width", hue="species",
truncate=True, height=5, data=iris)
# Use more informative axis labels than are provided by default
g.set_axis_labels("Sepal length (mm)", "Sepal width (mm)")
输出
19. seaborn.regplot()
句法
绘制数据和线性回归模型拟合。
import seaborn as sns; sns.set(color_codes=True)
tips = sns.load_dataset("tips")
ax = sns.regplot(x=x, y=y, marker="+")
输出
20.seaborn.residplot()
句法
绘制线性回归的残差。
import numpy as np
import seaborn as sns
sns.set(style="whitegrid")
# Make an example dataset with y ~ x
rs = np.random.RandomState(10)
x = rs.normal(2, 1, 75)
y = 2 + 1.5 * x + rs.normal(1, 2, 75)
# Plot the residuals after fitting a linear model
sns.residplot(x, y, lowess=True, color="g")
21. seaborn.heatmap()
句法
将矩形数据绘制为颜色编码矩阵。
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# Load the example flights dataset and conver to long-form
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
# Draw a heatmap with the numeric values in each cell
f, ax = plt.subplots(figsize=(9, 7))
sns.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax)
输出
22. seaborn.clustermap()
句法
将矩阵数据集绘制为分层聚类的热图。
import pandas as pd
import seaborn as sns
sns.set()
# Load the brain networks example dataset
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
# Select a subset of the networks
used_networks = [1, 5, 6, 7, 8, 12, 13, 17]
used_columns = (df.columns.get_level_values("network")
.astype(int)
.isin(used_networks))
df = df.loc[:, used_columns]
# Create a categorical palette to identify the networks
network_pal = sns.husl_palette(8, s=.45)
network_lut = dict(zip(map(str, used_networks), network_pal))
# Convert the palette to vectors that will be drawn on the side of the matrix
networks = df.columns.get_level_values("network")
network_colors = pd.Series(networks, index=df.columns).map(network_lut)
# Draw the full plot
sns.clustermap(df.corr(), center=0, cmap="vlag",
row_colors=network_colors, col_colors=network_colors,
linewidths=.75, figsize=(8, 8))
输出
结论
在本章中,我们学习了 Python Seaborn。在下一章中,我们将学习 Python Tensorflow。
Python Tensorflow 是一个非常有用的库,主要用于跨一系列任务的数据流和可微编程。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!
