用Seaborn轻松的进行数据可视化

代码中数据集下载链接:https://github.com/jsusu/Seaborn_data_visualization/tree/master/seaborn_data

import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
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()
sinplot()

# 1 五种主题风格:darkgrid,whitegrid,dark,white,ticks
sns.set_style("whitegrid")
data = np.random.normal(size=(20,6)) + np.arange(6)/2
sns.boxplot(data=data)
<matplotlib.axes._subplots.AxesSubplot at 0x105a32e10>

sns.set_style("dark")
sinplot()

在这里插入图片描述

sns.set_style("white")
sinplot()

sns.set_style("ticks")
sinplot()

sinplot()
sns.despine()

在这里插入图片描述

sns.violinplot(data)
sns.despine(offset=10) # offset:指定图离轴线的距离

在这里插入图片描述

sns.set_style("whitegrid")
sns.boxplot(data=data,palette="deep")
sns.despine(left=True)

在这里插入图片描述

with sns.axes_style("darkgrid"): # 指定一个with域
    plt.subplot(211)
    sinplot()
plt.subplot(212)
sinplot(-1)

在这里插入图片描述

sns.set()
sns.set_context("paper") 
plt.figure(figsize=(8,6))# 设置画图域的大小
sinplot()

在这里插入图片描述

sns.set_context("talk") 
plt.figure(figsize=(8,6))# 设置画图域的大小
sinplot()

在这里插入图片描述

sns.set_context("poster") 
plt.figure(figsize=(8,6))# 设置画图域的大小
sinplot()

在这里插入图片描述

sns.set_context("notebook",font_scale=1.5,rc={"lines.linewidth":2.5})
sinplot()# font_scale:字体大小,linewidth:线粗

在这里插入图片描述

# 2 调色板
# color_palette()能传入任何matplotlib支持的颜色,不写参数则默认颜色
# set_palette()设置所有图的颜色

sns.set(rc={"figure.figsize":(6,6)})

# 2.1 分类色板
current_palette = sns.color_palette()
sns.palplot(current_palette) # 默认色板颜色

在这里插入图片描述

# 2.2 圆形画板
# 当你有留个以上的分类要区分时,最简单的方法就是在一个圆形的颜色空间中画出均匀间隔的颜色
#(这样的色调会保持亮度和饱和度不变)
# 最常用的方法是使用his的颜色空间,这是RGB值的简单转换
sns.palplot(sns.color_palette("hls",8))

在这里插入图片描述

data = np.random.normal(size=(20,8))+np.arange(8)/2
sns.boxplot(data=data,palette=sns.color_palette("hls",8))
<matplotlib.axes._subplots.AxesSubplot at 0x105be5e90>

在这里插入图片描述

# 2.3画板颜色的亮度和饱和度
# l:亮度(lightness)
# s:饱和 saturation

sns.palplot(sns.hls_palette(8,l=0.3,s=0.8))

在这里插入图片描述

sns.palplot(sns.color_palette("Paired",10)) # 进行对比,一对一对的调色板

在这里插入图片描述

# 使用xkcd颜色来命名颜色
# xkcd包含了一套针对随机RGB的命名,产生了954个可以随时通过xkcd_rgb字典中调用的颜色命名
plt.plot([0,1],[0,1],sns.xkcd_rgb["pale red"],lw=3)
plt.plot([0,1],[0,2],sns.xkcd_rgb["medium green"],lw=3)
plt.plot([0,1],[0,3],sns.xkcd_rgb["denim blue"],lw=3)
[<matplotlib.lines.Line2D at 0x1a19d70e50>]

在这里插入图片描述

# 上面介绍的是离散的色板

# 2.4连续色板
# 色彩随数据变换

sns.palplot(sns.color_palette("Blues"))

在这里插入图片描述

# 翻转渐变-->添加一个_r后缀
sns.palplot(sns.color_palette("Blues_r"))

在这里插入图片描述

# 2.5 线性色板--->色调线性变换

sns.palplot(sns.color_palette("cubehelix",8))

在这里插入图片描述

sns.palplot(sns.cubehelix_palette(8,start=0.5,rot=-0.75))

在这里插入图片描述

sns.palplot(sns.cubehelix_palette(8,start=0.75,rot=-0.150))

在这里插入图片描述

# 2.6 light_palette和dark_palette调用定制连续调色板

sns.palplot(sns.light_palette("green"))

在这里插入图片描述

sns.palplot(sns.dark_palette("purple"))

在这里插入图片描述

# 反转
sns.palplot(sns.dark_palette("purple",reverse=True))

在这里插入图片描述

x, y = np.random.multivariate_normal([0,0],[[1,-0.5],[-0.5,1]], size=300).T
pal = sns.dark_palette("green",as_cmap=True)
sns.kdeplot(x, y,cmap=pal)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1ad6ac10>

在这里插入图片描述

sns.palplot(sns.light_palette((210,90,60), input="husl"))

在这里插入图片描述

# 3 单变量分析绘图
from scipy import stats, integrate
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "distributions")))
x = np.random.normal(size=100)
sns.distplot(x, kde=False)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1b491bd0>

在这里插入图片描述

sns.distplot(x, bins=20,kde=False)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1bb72510>

在这里插入图片描述

# 数据分布情况
x = np.random.gamma(6, size=200)
sns.distplot(x,kde=False,fit=stats.gamma) # fit:传入统计指标
<matplotlib.axes._subplots.AxesSubplot at 0x10333c590>

在这里插入图片描述

# 根据均值和协方差生存数据
mean, cov = [0,1],[(1,0.5),(0.5,1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x","y"])
df
xy
02.1908732.902961
10.3879013.441322
2-1.3049090.586173
3-0.0168670.907323
40.2849531.189304
.........
195-0.8043380.139381
1961.6743932.735944
197-1.2376340.002766
198-1.0446830.482758
199-0.8901600.042753

200 rows × 2 columns

# 观测两个变量(特征)之间的分布关系最好用散点图
sns.jointplot(x="x",y="y",data=df)
<seaborn.axisgrid.JointGrid at 0x1a1bfd9610>

在这里插入图片描述

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")
# 颜色越深,当前点比较多

在这里插入图片描述

# 多特征显示
iris = sns.load_dataset("iris")
sns.pairplot(iris) # 将数据四个特征中两两之间的关系画出
<seaborn.axisgrid.PairGrid at 0x1a1d34abd0>

在这里插入图片描述

# 4.回归分析绘图
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "regression")))
tips = sns.load_dataset("tips")
tips.head()
total_billtipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4
sns.regplot(x="size",y="tip",data=tips, x_jitter=0.5)
# sns.lmplot()
<matplotlib.axes._subplots.AxesSubplot at 0x1a1da4f690>

在这里插入图片描述

# 5.多变量分析绘图

sns.set(style="whitegrid",color_codes=True)

np.random.seed(sum(map(ord, "categorical")))
titanic = sns.load_dataset("titanic")
# print(titanic.head())
tips = sns.load_dataset("tips")
iris = sns.load_dataset("iris")
# 5.1 stropplot()
sns.stripplot(x="day",y="total_bill",data=tips)
   survived  pclass     sex   age  sibsp  parch     fare embarked  class  \
0         0       3    male  22.0      1      0   7.2500        S  Third   
1         1       1  female  38.0      1      0  71.2833        C  First   
2         1       3  female  26.0      0      0   7.9250        S  Third   
3         1       1  female  35.0      1      0  53.1000        S  First   
4         0       3    male  35.0      0      0   8.0500        S  Third   

     who  adult_male deck  embark_town alive  alone  
0    man        True  NaN  Southampton    no  False  
1  woman       False    C    Cherbourg   yes  False  
2  woman       False  NaN  Southampton   yes   True  
3  woman       False    C  Southampton   yes  False  
4    man        True  NaN  Southampton    no   True  





<matplotlib.axes._subplots.AxesSubplot at 0x1a1f4e4210>

在这里插入图片描述

# 重叠是很常见的现象,但影响我们观察数据量
sns.stripplot(x="day",y="total_bill",data=tips, jitter=True)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1e445c50>

在这里插入图片描述

# 5.2 swarmplot()
sns.swarmplot(x="day",y="total_bill",data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1eca5ed0>

在这里插入图片描述

sns.swarmplot(x="day",y="total_bill",hue="sex", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1eca5650>

在这里插入图片描述

sns.swarmplot(x="day",y="total_bill",hue="time", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1e9d6c90>

在这里插入图片描述

# 5.3 盒图--boxplot
# IQR即统计学概念四分位距,第一/四分位与第三/四分位之间的距离
# N=1.5IQR 如果一个值>Q3+N 或<Q1-N,则为离群点

sns.boxplot(x="day", y="total_bill", hue="time", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1fbfab10>

在这里插入图片描述

# 使盒图横着画-->orient="h"
sns.boxplot(orient="h", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1fe81d50>

在这里插入图片描述

# 5.4 小提琴图--violinplot()
sns.violinplot(y="day", x="total_bill", hue="time", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1e83c090>

在这里插入图片描述

sns.violinplot(x="day", y="total_bill",split=True, hue="sex", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1e3a7250>

在这里插入图片描述

# 多种图进行合并
sns.violinplot(x="day", y="total_bill", inner=None, data=tips)
sns.swarmplot(x="day", y="total_bill", color="w",alpha=0.5, data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1edeb590>

在这里插入图片描述

# 5.5 条形图--barplot()
# 显示值的集中趋势

sns.barplot(x="sex",y="survived", hue="class", data=titanic)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1fb8fb90>

在这里插入图片描述

# 5.6 点图--pointplot()

sns.pointplot(x="sex",y="survived", hue="class", data=titanic)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1fbf1190>

在这里插入图片描述

sns.pointplot(x="class",y="survived",hue="sex",data=titanic,
              palette={"male":"g","female":"m"},
             markers=["^","o"],linestyles=["-","--"])
<matplotlib.axes._subplots.AxesSubplot at 0x1a1fcdf790>

在这里插入图片描述

# 5.7 多层面板分类图-->factorplot()

sns.factorplot(x="day", y="total_bill",hue="smoker",data=tips)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/categorical.py:3669: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
  warnings.warn(msg)





<seaborn.axisgrid.FacetGrid at 0x1a200f9210>

在这里插入图片描述

sns.factorplot(x="day", y="total_bill",hue="smoker",data=tips,kind="bar")
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/categorical.py:3669: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
  warnings.warn(msg)





<seaborn.axisgrid.FacetGrid at 0x1a203d0c10>

在这里插入图片描述

sns.factorplot(x="day", y="total_bill",col="time",hue="smoker",data=tips,kind="swarm")
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/categorical.py:3669: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
  warnings.warn(msg)





<seaborn.axisgrid.FacetGrid at 0x1a1f5003d0>

在这里插入图片描述

sns.factorplot(x="time", y="total_bill",hue="smoker",data=tips,kind="box",
              col="day",size=4,aspect=0.5)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/categorical.py:3669: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
  warnings.warn(msg)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/categorical.py:3675: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
  warnings.warn(msg, UserWarning)





<seaborn.axisgrid.FacetGrid at 0x1a1e45a550>

在这里插入图片描述

# factorplot()常用的parameters:

# x,y,hue 数据集变量 变量名
# data 数据集 数据集名
# row,col 更多分类变量进行平铺显示 变量名
# col_wrap每行的最高平铺数 整数
# estimator 在每个分类中进行矢量到标量的映射 矢量
# ci 置信区间 浮点数或none
# n_boot 计算置信区间时使用的引导迭代次数 整数
# units 采样单元的标识符,用于执行多级引导和重复测量设计 数据变量或向量数据
# order,hue_order 对应排序列表 字符串列表
# row_order,col_order 对应排序列表 字符串列表
# kind :可选(point默认,bar柱状图,count频次,box箱体,violin提琴,strip散点,swarm分散点,size每个面的高度(英寸)
# 标量,aspect纵横比 标量,orient方向:“v”/"h",color颜色,matplotlib颜色 ,palette调色板:seaborn颜色色板或字典,legend hue的信息面板 True/False 
# legend_out是否扩展图形,并将信息框绘制在中心右边 True/False
# share{x,y}共享轴线 True/False)
# 6.FaceGrid()绘制多变量

tips.head()
total_billtipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4
g = sns.FacetGrid(tips,col="time") # 先去布局,相当于占位置

在这里插入图片描述

g = sns.FacetGrid(tips,col="time")
g.map(plt.hist, "tip")
<seaborn.axisgrid.FacetGrid at 0x1a211dd8d0>

在这里插入图片描述

g = sns.FacetGrid(tips, col="sex", hue="smoker")
g.map(plt.scatter, "total_bill", "tip",alpha=0.7)
g.add_legend() # 添加图例
<seaborn.axisgrid.FacetGrid at 0x1a21361b50>

在这里插入图片描述

g = sns.FacetGrid(tips, row="smoker",col="time", margin_titles=True)
g.map(sns.regplot, "size","total_bill",color="0.3",
      fit_reg=True,# fit_reg是否显示回归线
      x_jitter=0.1)# jitter浮动
<seaborn.axisgrid.FacetGrid at 0x1a21ded350>

在这里插入图片描述

g = sns.FacetGrid(tips,col="day",size=4,aspect=0.5)
g.map(sns.barplot, "sex", "total_bill")
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/axisgrid.py:243: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
  warnings.warn(msg, UserWarning)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/axisgrid.py:728: UserWarning: Using the barplot function without specifying `order` is likely to produce an incorrect plot.
  warnings.warn(warning)





<seaborn.axisgrid.FacetGrid at 0x1a224f5850>

在这里插入图片描述

from pandas import Categorical
ordered_days = tips.day.value_counts().index
print(order_days)
# ordered_days = Categorical(["Thur","Fri","Sat","Sun"])
g = sns.FacetGrid(tips,row="day",row_order=ordered_days,
                 size=1.7,aspect=4) # size被替换成height
g.map(sns.boxplot,"total_bill")
CategoricalIndex(['Sat', 'Sun', 'Thur', 'Fri'], categories=['Thur', 'Fri', 'Sat', 'Sun'], ordered=False, dtype='category')


/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/axisgrid.py:243: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
  warnings.warn(msg, UserWarning)
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/axisgrid.py:728: UserWarning: Using the boxplot function without specifying `order` is likely to produce an incorrect plot.
  warnings.warn(warning)





<seaborn.axisgrid.FacetGrid at 0x1a240e54d0>

在这里插入图片描述

pal = dict(Lunch="seagreen",Dinner="gray")
g = sns.FacetGrid(tips,hue="time",palette=pal,height=5)
g.map(plt.scatter, "total_bill","tip", s=50,alpha=0.7,linewidth=0.5,edgecolor="white")
g.add_legend()
<seaborn.axisgrid.FacetGrid at 0x1a24220550>

在这里插入图片描述

g = sns.FacetGrid(tips,hue="sex",palette="Set1",size=5,
                 hue_kws={"marker":["^","v"]})
g.map(plt.scatter, "total_bill","tip", s=100,alpha=0.7,
      linewidth=0.5,edgecolor="white")
g.add_legend()
<seaborn.axisgrid.FacetGrid at 0x1a241e1a90>

在这里插入图片描述

with sns.axes_style("white"):
    g = sns.FacetGrid(tips, row="sex", col="smoker", margin_titles=True,
                     size=2.5)
g.map(plt.scatter, "total_bill","tip",color="#334488",edgecolor="white",lw=0.5)
g.set_axis_labels("Total bill(US Dollars)", "Tip")
g.set(xticks=[10,30,50], yticks=[2,6,10]) #x,y轴刻度范围
g.fig.subplots_adjust(wspace=0.2, hspace=0.2# 设置子图间隔
/Users/susu/opt/anaconda3/envs/data_analysis/lib/python3.7/site-packages/seaborn/axisgrid.py:243: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
  warnings.warn(msg, UserWarning)

在这里插入图片描述

iris = sns.load_dataset("iris")
g = sns.PairGrid(iris)
g.map(plt.scatter)

<seaborn.axisgrid.PairGrid at 0x1a24841050>

在这里插入图片描述

g = sns.PairGrid(iris)
g.map_diag(plt.hist) # 指定对角线的图
g.map_offdiag(plt.scatter) # 指定非对角线的图
<seaborn.axisgrid.PairGrid at 0x1a24ee9810>

在这里插入图片描述

g = sns.PairGrid(iris,hue="species")
g.map_diag(plt.hist) # 指定对角线的图
g.map_offdiag(plt.scatter) # 指定非对角线的图
g.add_legend()
<seaborn.axisgrid.PairGrid at 0x1a259de0d0>

在这里插入图片描述

g = sns.PairGrid(iris,hue="species",
                 vars=["sepal_length","sepal_width"]) # vars:指定需要绘制的特征
g.map(plt.scatter)
<seaborn.axisgrid.PairGrid at 0x1a26bb7590>

在这里插入图片描述

g = sns.PairGrid(tips,hue="size",palette="GnBu_d")
g.map(plt.scatter,s=50,edgecolor="white")
g.add_legend()
<seaborn.axisgrid.PairGrid at 0x1a26da8910>

在这里插入图片描述

# 7.热度图--->heatmap()
# 常用于特征与特征的相关程度
%matplotlib inline
import numpy as np
import pandas as pd
import seaborn as sns
np.random.seed(0)
sns.set()
uniform_data = np.random.rand(3,3)
print(uniform_data)
heatmap = sns.heatmap(uniform_data)
[[0.11402723 0.39613034 0.86002087]
 [0.10145661 0.06316734 0.54688621]
 [0.9487925  0.82667995 0.85134329]]

在这里插入图片描述

ax = sns.heatmap(uniform_data,vmin=0.2,vmax=0.5) # 指定color bar的范围

在这里插入图片描述

normal_data = np.random.randn(3,3)
print(normal_data)
ax = sns.heatmap(normal_data,center=0) # center指定中心的数据
[[-0.51964495 -0.55467919 -1.51977748]
 [-0.95065924 -0.14189382 -0.75598294]
 [ 0.54360754  0.35617477 -0.92938628]]

在这里插入图片描述

flights = sns.load_dataset("flights")
flights.head()
yearmonthpassengers
01949January112
11949February118
21949March132
31949April129
41949May121
flights = flights.pivot("month","year","passengers")
print(flights)
ax = sns.heatmap(flights)
year       1949  1950  1951  1952  1953  1954  1955  1956  1957  1958  1959  \
month                                                                         
January     112   115   145   171   196   204   242   284   315   340   360   
February    118   126   150   180   196   188   233   277   301   318   342   
March       132   141   178   193   236   235   267   317   356   362   406   
April       129   135   163   181   235   227   269   313   348   348   396   
May         121   125   172   183   229   234   270   318   355   363   420   
June        135   149   178   218   243   264   315   374   422   435   472   
July        148   170   199   230   264   302   364   413   465   491   548   
August      148   170   199   242   272   293   347   405   467   505   559   
September   136   158   184   209   237   259   312   355   404   404   463   
October     119   133   162   191   211   229   274   306   347   359   407   
November    104   114   146   172   180   203   237   271   305   310   362   
December    118   140   166   194   201   229   278   306   336   337   405   

year       1960  
month            
January     417  
February    391  
March       419  
April       461  
May         472  
June        535  
July        622  
August      606  
September   508  
October     461  
November    390  
December    432  

在这里插入图片描述

ax = sns.heatmap(flights,
                 annot=True,# annot将数据绘制到图上
                 fmt="d", # 指定数据的格式,比较推荐
                 linewidths=0.5, #指定格与格之间的间距
                 cmap="YlGnBu",# 指定colorbar颜色
                 cbar=False, # False为隐藏colorbar
                ) 

在这里插入图片描述


End:如果你看到了这里,那么一定是将这一整篇都阅读喽,恭喜你,基本的seaborn已经学会了哦~~~

  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值