seaborn学习笔记
导入seaborn库
seaborn是基于matplotlib简化的python绘图库 所以一般与numpy pandas matplotlib库一同使用 所以我们一同导入四个库
import seaborn as sns
import numpy as np
import pandas an pd
import matplotlib.pyplot as plt
使用set()语句绘制seaborn默认绘图
先自定义生成一个正弦函数 输出它的图像
def sinplot(flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, 7):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sinplot()
plt.show()
得到图像
下面使用set()语句绘制seaborn默认图像
sns.set()
seaborn可以直接控制matplotlib中图像的风格和大小比例
控制风格:axes_style(), set_style()
缩放绘图:plotting_context(), set_context()
seaborn的五种绘画风格
seaborn提供了五种绘画风格 分别为
darkgrid, whitegrid, dark, white, ticks
默认风格为darkgrid
移除不需要的坐标轴
在seaborn中可以使用 despine() 语句来移除不需要的坐标轴 这一点与matplotlib中的ax.spines[].set_color(‘none’)类似
注意 只能在white和ticks风格中移除坐标轴
def sinplot(flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, 7):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sinplot()
sns.set_style('white')
sns.despine()
plt.show()
得到图像
移动坐标轴
在seaborn中同样可以使用despine()语句移动坐标轴的位置
def sinplot(flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, 7):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sinplot()
sns.set_style('white')
sns.despine(offset=10, trim=True)
plt.show()
得到图像
绘制元素比例
seaborn提供了四个预置的比例 分别为
paper, notebook, talk, poster
其中默认为notebook
设置颜色风格
建立调色板
有三种通用的color palette可以使用 分别为
qualitative,sequential,diverging
分类色板 qualitative
seaborn带有六种默认主题 分别为
deep,muted,pastel,birght,dark,colorblind
上图为dark与pastel
使用色圈系统
使用hls()语句可以转换RGB的值
使用hls_palette()语句可以改变hls的亮度和饱满度
连续色板 sequential
使用sns.palplot(sns.color_palette())语句可以生成连续的色板
sns.palplot(sns.color_palette("Blues"))
plt.show()
得到图像
离散色板
在连续色板的括号中加上数字 即可生成离散色板
sns.palplot(sns.color_palette("Blues",10))
plt.show()
得到图像
数据分析可视化
绘制单变量分布
在seaborn中可以使用distplot()语句绘制单个变量的图像
x = np.random.normal(size=100)
sns.distplot(x);
plt.show()
得到图像
绘制直方图
使用distplot()可以直接绘制直方图
x = np.random.normal(size=100)
sns.distplot(x, kde=False, rug=True);
plt.show()
得到图像
其中 使用bins= 语句可以改变直方图中矩形的数量
x = np.random.normal(size=100)
sns.distplot(x, bins=20,kde=False, rug=True);
plt.show()
得到图像
绘制双变量分布
使用joinplot()语句可以直接绘制双变量分布
散点图 Scatterplots
mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])
sns.jointplot(x="x", y="y", data=df)
plt.show()
得到图像
蜂箱图 Hexbin plots
mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])
x, y = np.random.multivariate_normal(mean, cov, 1000).T
with sns.axes_style("white"):
sns.jointplot(x=x, y=y, kind="hex", color="k");
plt.show()
得到图像
核密度估计图 Kernel density estimation
mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])
x, y = np.random.multivariate_normal(mean, cov, 1000).T
sns.jointplot(x="x", y="y", data=df, kind="kde");
plt.show()
得到图像