简介
虽然Matplotlib库已经能够完成大部分的绘图任务,但是有时候图表并不是非常好看,而Seaborn库提供了更加高级的接口和许多定制的主题,使作图更加美观。也就是说,它是对Matplotlib库的补充。
Matplotlib的作图效果
我们来看一个例子:
1 2 3 4 5 6 7 8 9 10 |
import numpy as np import matplotlib.pyplot as plt def plot_sin(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) plot_sin() plt.show() |
首先导入必要的库,然后定义一个函数用来画正弦函数,通过设置不同的偏移量,得到6条曲线。这是常规的Matplotlib作图方式,得到如下图形:
Seaborn的作图效果
通过以下代码引入Seaborn库:
1 2 3 4 5 6 7 8 9 10 11 12 |
import numpy as np import matplotlib.pyplot as plt import seaborn as sns def plot_sin(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) sns.set() plot_sin() plt.show() |
首先通过 import seaborn as sns 导入Seaborn库,在正常的画图步骤前,要通过 sns.set() 设置绘图风格。默认的 sns.set() 方法如下:
1 |
set(context="notebook", style="darkgrid", palette="deep", font="sans-serif", font_scale=1, color_codes=False, rc=None) |
通过 context 参数设置图片的大小尺寸,通过 style 设置背景的风格,另外还有设置颜色的参数等。最终得到如下图:
Seaborn提供了5种预定义的主题:
- darkgrid:灰色背景+白网格
- whitegrid:白色背景+黑网格
- dark:灰色背景
- white:白色背景
- ticks:坐标轴带刻度
使用Seaborn作图时,默认使用浅灰色背景与白色网格线。而要更改背景主题可以使用 set_style() 函数,或者在 set() 通过传入 style 参数,这两者是等价的。比如以下示例:
1 2 3 4 5 6 7 8 9 10 11 12 |
import numpy as np import matplotlib.pyplot as plt import seaborn as sns def plot_sin(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) sns.set_style('whitegrid') # 等价于 sns.set(style='whitegrid') plot_sin() plt.show() |
在这里将背景的风格修改成白底黑网格,得到如下图形:
更改尺寸大小可以使用 set_context() 函数,或者在 set() 通过传入 context 参数。Seaborn中预定义的上下文有4种:
- paper
- notebook
- talk
- poster
默认使用的是notebook,这几种定义使得图片的size和粗细依次递增。具体通过以下代码查看效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import numpy as np import matplotlib.pyplot as plt import seaborn as sns def plot_sin(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) plt.figure(figsize=(12, 8)) sns.set() plt.subplot(221) plot_sin() sns.set(context='paper', style='whitegrid') plt.subplot(222) plot_sin() sns.set(context='talk', style='dark') plt.subplot(223) plot_sin() sns.set(context='poster', style='white') plt.subplot(224) plot_sin() plt.show() |
最终得到如下图片:
sns的设置需要在画子图之前就定义好,如果放在 plt.subplot() 的后面就错了。并且可以看出图像曲线的线宽和坐标字体大小发生比较明显的变化。
Seaborn除了改变背景格式,画布大小,还有其他有意思的功能。比如以下的例子:
1 2 3 4 5 6 7 8 9 |
import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() # 使用默认设置 data = sns.load_dataset('flights') # 加载sns自带数据集 data = data.pivot('month', 'year', 'passengers') sns.heatmap(data, annot=True, fmt='d', lw=0.5, cmap="YlGnBu") plt.show() |
在这里调用了sns的 heatmap() 函数作热图,其中 annot 参数控制数值是否显示, fmt 参数控制数值的格式, lw 参数为线宽, cmap 参数控制使用的颜色模式。最终得到如下图:
总结
在本文中简单介绍了一个高级的作图库Seaborn,讲解了如何简单地设置背景风格和图形风格。需要注意的是,Seaborn的设置必须在作图函数前就要定义好。该库能够做出更多漂亮、有趣的图形,如果有兴趣可以查看官网的文档和示例图片。