Seaborn 究竟是什么?
基于 matplotlib and Pandas,用更简单的调用呈现更多美图~ 鱼与熊掌兼得~
If matplotlib “tries to make easy things easy and hard things possible”, seaborn tries to make a well-defined set of hard things easy too.
OFFICIAL: http://seaborn.pydata.org
Seaborn 风格管理
%matplotlib inline
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
np.random.seed(sum(map(ord, "aesthetics"))) # 给每一个任务单独分配随机种子
先来看看matplotlib画出来的图啥样子~
def sinplot(flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, 7): # up to but not include
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sinplot()
再来看看seaborn画出来滴:
import seaborn as sns
sns.set()
sinplot()
# 色彩柔和!灰色背景!白色网格!
- 风格参数设置
- 尺度参数设置
风格参数设置
就下面5种主题风格:
- darkgrid/whitegrid(深色带格子/白色带格子):更关注数值,所以带格子嘛~
- dark/white:更关注整体趋势
- ticks:强化刻度
sns.set_style("darkgrid")
sinplot()
sns.set_style("ticks")
sinplot()
sns.despine() # despine()函数是去掉了上右边框
sinplot()
sns.despine(offset=50) # offset参数可以调节分离坐标轴
尺度参数设置
sns.set_context("paper")
# 比如用于期刊论文
sinplot()
sns.set_context("notebook")
# 比如用于本notebook文档
sinplot()
sns.set_context("talk") # 比如需要嵌入到ppt中
sinplot()
sns.set_context("poster") # 比如用于展板
sinplot()
# 可以微调
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 1.5})
sinplot()
颜色管理
- 分类调色板
- 序列调色板
- 分叉调色板
分类调色板
- 适用于分类描述的数据,而且分类之间无序
- 两个颜色系统:
- hls颜色系统(默认),色调+亮度+饱和度(hue + luminance + saturation)
- husl颜色系统,hls中不同颜色存在视差,eg.黄色偏亮,蓝色偏暗,husl使得更加平衡
# 恢复默认设置
sns.set()
# 绘制当前调色板
current_palette = sns.color_palette()
sns.palplot(current_palette)
# 绘制hls系统下的10色调色板(黄色偏暗 蓝色偏亮)
sns.set_palette(sns.color_palette("hls", 10))
current_palette = sns.color_palette()
sns.palplot(current_palette)
# 绘制husl系统下的10色调色板(与hls相比,色彩不突兀)
sns.set_palette(sns.color_palette("husl", 10)) # http://www.hsluv.org
current_palette = sns.color_palette()
sns.palplot(current_palette)
sns.set() # 默认调色板
sinplot()
sns.set_palette(sns.color_palette("hls", 10))
sinplot()
sns.set_palette(sns.color_palette("husl", 10))
sinplot()
序列调色板
- 主要通过亮度和饱和度区分有序分类
- 关注单级数据
sns.palplot(sns.color_palette("Greens",10))
with sns.color_palette("Greens_d"):
sinplot()
分叉调色板
- 关注两级数据
sns.palplot(sns.color_palette("autumn",11)) # 比如表示温度梯度
sns.palplot(sns.diverging_palette(10,220,sep=80,n=11))
- 关注多级数据
sns.palplot(sns.diverging_palette(255, 133, l=60, n=10, center="dark"))
with sns.diverging_palette(255, 133, l=60, n=5, center="dark"):
sinplot()
小结
- 引入seaborn: import seaborn as sns
- 恢复默认设置: sns.set(), mpl.rcdefaults()
- 设置风格: sns.set_style(“xxxx”)
- 设置大小: sns.set_context(“xxxx”)
- 设置调色板: sns.set_palette(sns.color_palette(“hls”, 8))
源码获取:关注微信公众号“AI阅读知识图谱”,回复“Python数据可视化”获取已更新内容全部代码。