利用Seaborn进行绘图
下面例子中所用数据下载地址——>iris.csv
Matplotlib绘图基本模仿MATLAB绘图库,其绘图风格和MATLAB类似。由于MATLAB绘图风格偏古典,因此,Python开源社区开发了Seaborn绘图模块,对Matplotlib进行封装,绘图效果更符合现代人的审美。
Seaborn属于Matplotlib的一个高级接口,使得作图更加容易。在多数情况下使用Seaborn能做出很具吸引力的图,而使用Matplotlib可以制作具有更多特色的图。应该把Seaborn视为iris.csvMatplotlib的补充,而不是替代物。
使用Seaborn时,使用的导入惯例为:
import seaborn as sns
风格设置用以设置绘图的背景色、风格、字型、字体等。
Seaborn通过set函数实现风格设置。
seaborn.set(context=‘notebook’, style=‘darkgrid’, palette=‘deep’, font=‘sans-serif’, font_scale=1, color_codes=True, rc=None)
利用seaborn.set进行风格设置
import seaborn as sns
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def sinplot(flip=2):
x = np.linspace(0,20, 50)
for i in range(1,5):
plt.plot(x, np.cos(x + i * 0.8) * (9 - 2*i) * flip)
sinplot()
sns.set(style='darkgrid',font_scale=1.5)
sinplot()
如果需要转换为seaborn默认的绘图设置,只需调用sns.set( )方法即可。
sns.set()
sinplot()
设置主题
利用set_style( )是用来设置主题的。
Seaborn有五个预设好的主题: darkgrid, whitegrid,dark,white,和 ticks,默认为darkgrid。
sns.set_style("whitegrid")
sinplot()
Seaborn将matplotlib的参数划分为两个独立的组合。第一组是设置绘图的外观风格的,第二组主要将绘图的各种元素按比例缩放的,以至可以嵌入到不同的背景环境中。控制这些参数的接口主要有两对方法:
控制风格:axes_style(), set_style()
缩放绘图:plotting_context(), set_context()
每对方法中的第一个方法(axes_style(), plotting_context())会返回一组字典参数,而第二个方法(set_style(), set_context())会设置matplotlib的默认参数。
利用set_style( )是用来设置主题的。Seaborn有五个预设的主题: darkgrid, whitegrid,dark,white,和 ticks,默认为darkgrid。
sns.set_style("whitegrid")
sinplot()
在seaborn中,可以利用despine()方法移除绘图中顶部和右侧的轴线。
sinplot()
sns.despine()
despine()方法中可以利用offset参数