什么是Seaborn
Seaborn是基于matplotlib的图形可视化python包。它提供了一种高度交互式界面,便于用户能够做出各种有吸引力的统计图表。
Seaborn是在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,在大多数情况下使用seaborn能做出很具有吸引力的图,而使用matplotlib就能制作具有更多特色的图。应该把Seaborn视为matplotlib的补充,而不是替代物。同时它能高度兼容numpy与pandas数据结构以及scipy与statsmodels等统计模式。
seaborn API
Seaborn 要求原始数据的输入类型为 pandas 的 Dataframe 或 Numpy 数组,画图函数有以下几种形式:
sns.图名(x=‘X轴 列名’, y=‘Y轴 列名’, data=原始数据df对象)
sns.图名(x=‘X轴 列名’, y=‘Y轴 列名’, hue=‘分组绘图参数’, data=原始数据df对象)
sns.图名(x=np.array, y=np.array[, …])
整体风格设置
对图表整体颜色、比例等进行风格设置,包括颜色色板等
调用系统风格进行数据可视化
set() / set_style() / axes_style() / set_context()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set() 设置样式参数
seaborn.set(context =‘notebook’,style =‘darkgrid’,palette =‘deep’,font =‘sans-serif’,font_scale = 1,color_codes = True,rc = None)
# 创建正弦函数及图表
def sinplot(flip=1):
x = np.linspace(0,14,100)
for i in range(1,7):
plt.plot(x, np.sin(x+i*0.5)*(7-i)*flip)
sinplot()
sns.set() # 暗格显示
sinplot()
plt.grid(linestyle = '--')
set_style() 设置图标风格
seaborn.set_style(style = None,rc = None )
# set_style()
# 切换seaborn图表风格
# 风格选择包括:"white", "dark", "whitegrid", "darkgrid", "ticks"
# rc:dict,可选,参数映射以覆盖预设的seaborn样式字典中的值
fig = plt.figure(figsize=(6,6))
ax1 = fig.add_subplot(2,1,1)
sns.set_style("whitegrid")
data = np.random.normal(size=(20,6)) + np.arange(6)/2
sns.boxplot(data=data)
plt.title('style - whitegrid')
ax2 = fig.add_subplot(2,1,2)
#sns.set_style("dark")
sinplot() # 子图显示
sns.despine() 设置坐标轴
'''
despine()
设置图表坐标轴
seaborn.despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False, offset=None, trim=False)
'''
# 设置风格
sns.set_style("ticks")
# 创建图表
fig= plt.figure(figsize=(6,9))
plt.subplots_adjust(hspace=0.3) # 调整子图间距
ax1= fig.add_subplot(3,1,1)
sinplot()
sns.despine() # 默认删除上、右坐标轴
ax2 = fig.add_subplot(3,1,2)
sns.violinplot(data=data)
#sns.despine(offset=10,trim=True) # offset: 与坐标轴之间的偏移,trim: 为True时,将坐标轴限制在数据最大最小值
ax3