掘金 阅读 ( ) • 2024-04-19 12:01

Seaborn 是一个基于 matplotlib 的 Python 数据可视化库。它提供了一个高级界面,用于绘制有吸引力且信息丰富的统计图形。 官网地址

安装

pip3 install matplotlib

pip3 install Seabrn

要先安装 matplotlib

入门例子

import seaborn as sns
import matplotlib.pyplot as plt
​
# 生成一个柱形图
sns.barplot(x=["A", "B", "C"], y=[1, 3, 2])
# 生成图像
plt.show()

效果如下

image.png

可以使用 set_theme() 添加主题(背景色,字体颜色,字体大小等等)。

在 set_theme() 有多个参数可以定制化主题,如果没有传入参数也会有默认的主题

示例

import seaborn as sns
import matplotlib.pyplot as plt
​
sns.set_theme()
# 生成一个柱形图
sns.barplot(x=["A", "B", "C"], y=[1, 3, 2])
plt.show()

image.png

与第一个图相比样式明显有了很大的变化

set_theme()

官网 set_theme() 的api 官网上介绍了参数的使用

如下示例改变了轴的样式

import seaborn as sns
import matplotlib.pyplot as plt
​
​
sns.set_theme(style="ticks")
sns.barplot(x=["A", "B", "C"], y=[1, 3, 2])
​
plt.show()

image.png

参数 style 可以改变坐标轴的样式,如果使用的时传入的参数是 str

就只有固定的几个参数 white、 dark、 whitegrid、 darkgrid、ticks 使用别的会报错

import seaborn as sns
import matplotlib.pyplot as plt
​
sns.set_theme(style="whitegrid")
sns.barplot(x=["A", "B", "C"], y=[1, 3, 2])
​
plt.show()

image.png

rc 参数可以覆盖任何 seaborn 参数(包括之前设置的),还能使用属于 matplotlib rc 系统但未包含在 seaborn 主题中的其他参数

如下展示了将桌标轴都去掉的效果

import seaborn as sns
import matplotlib.pyplot as plt
​
custom_params = {"axes.spines.right": False, "axes.spines.top": False, "axes.spines.bottom": False, "axes.spines.left": False}
sns.set_theme(style="whitegrid", rc=custom_params)
sns.barplot(x=["A", "B", "C"], y=[1, 3, 2])
​
plt.show()

image.png