11 绘图实例(3) Drawing example(3)(代码下载)

本文主要讲述seaborn官网相关函数绘图实例。具体内容有:

  1. Plotting a diagonal correlation matrix(heatmap)
  2. Scatterplot with marginal ticks(JointGrid)
  3. Multiple bivariate KDE plots(kdeplot)
  4. Multiple linear regression(lmplot)
  5. Paired density and scatterplot matrix(PairGrid)
  6. Paired categorical plots(PairGrid)
  7. Dot plot with several variables(PairGrid)
  8. Plotting a three-way ANOVA(catplot)
  9. Linear regression with marginal distributions(jointplot)
  10. Plotting model residuals(residplot)
# import packages
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

1. Plotting a diagonal correlation matrix(heatmap)

# 读取字母表
from string import ascii_letters # Generate a large random dataset 生成数据集
rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 26)),
columns=list(ascii_letters[26:])) # Compute the correlation matrix 计算相关系数
corr = d.corr() # Generate a mask for the upper triangle 生成掩模
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True d# Set up the matplotlib figure 设置图大小
f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap 设置颜色
cmap = sns.diverging_palette(220, 10, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio
# square表都是正方形
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5});

2. Scatterplot with marginal ticks(JointGrid)

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

# Generate a random bivariate dataset
rs = np.random.RandomState(9)
mean = [0, 0]
cov = [(1, 0), (0, 2)]
x, y = rs.multivariate_normal(mean, cov, 100).T # Use JointGrid directly to draw a custom plot
# 创建一个绘图表格区域,设置好x,y对应数据
grid = sns.JointGrid(x, y, space=0, height=6, ratio=50)
# 在联合分布上画出散点图
grid.plot_joint(plt.scatter, color="g")
# 在边缘分布上再作图
grid.plot_marginals(sns.rugplot, height=1, color="g");
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\tight_layout.py:199: UserWarning: Tight layout not applied. tight_layout cannot make axes width small enough to accommodate all axes decorations
warnings.warn('Tight layout not applied. '

3. Multiple bivariate KDE plots(kdeplot)

sns.set(style="darkgrid")
iris = sns.load_dataset("iris") # Subset the iris dataset by species
# 单独筛选对应类的数据
setosa = iris.query("species == 'setosa'")
virginica = iris.query("species == 'virginica'") # Set up the figure
f, ax = plt.subplots(figsize=(8, 8))
# 设置轴的缩放比例,equal表示x,y轴同等缩放比例
ax.set_aspect("equal") # Draw the two density plots
# 画核密度图
# shade表示添加阴影,shade_lowest表示两个核密度图相叠时,核密度小的部分不画出来
ax = sns.kdeplot(setosa.sepal_width, setosa.sepal_length,
cmap="Reds", shade=True, shade_lowest=False)
ax = sns.kdeplot(virginica.sepal_width, virginica.sepal_length,
cmap="Blues", shade=True, shade_lowest=False) # Add labels to the plot
# 添加颜色
red = sns.color_palette("Reds")[-2]
blue = sns.color_palette("Blues")[-2]
ax.text(2.5, 8.2, "virginica", size=16, color=blue)
ax.text(3.8, 4.5, "setosa", size=16, color=red);
C:\ProgramData\Anaconda3\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval

4. Multiple linear regression(lmplot)

# Load the iris dataset 读取数据
iris = sns.load_dataset("iris") # Plot sepal with as a function of sepal_length across days
# 画散点图,lmplot默认参数,以hue设定不同种类
# truncate为true表示现植回归拟合曲线绘图时只画出有数据的部分
g = sns.lmplot(x="sepal_length", y="sepal_width", hue="species",
truncate=True, height=5, data=iris); # Use more informative axis labels than are provided by default
# 设置横竖坐标轴label
g.set_axis_labels("Sepal length (mm)", "Sepal width (mm)");

5. Paired density and scatterplot matrix(PairGrid)

sns.set(style="white")

df = sns.load_dataset("iris")
# 制作散点图矩阵
# diag_sharey是否共享y轴
g = sns.PairGrid(df, diag_sharey=False)
# 下三角绘多变量核密度图
g.map_lower(sns.kdeplot)
# 上三角绘散点图
g.map_upper(sns.scatterplot)
# 对角线绘单变量核密度图,lw表示线条粗细
g.map_diag(sns.kdeplot, lw=3);

6. Paired categorical plots(PairGrid)

sns.set(style="whitegrid")

# Load the example Titanic dataset
titanic = sns.load_dataset("titanic") # Set up a grid to plot survival probability against several variables
# 制作散点图矩阵
# y轴为survived值,x_vars设定x轴
g = sns.PairGrid(titanic, y_vars="survived",
x_vars=["class", "sex", "who", "alone"],
height=5, aspect=.5)
# Draw a seaborn pointplot onto each Axes
# 制作折线图, errwidth表示上下标准注的长度,其中各点代表平均值
g.map(sns.pointplot, scale=1.3, errwidth=4, color="xkcd:plum")
g.set(ylim=(0, 1))
sns.despine(fig=g.fig, left=True);

7. Dot plot with several variables(PairGrid)

sns.set(style="whitegrid")

# Load the dataset
crashes = sns.load_dataset("car_crashes") # Make the PairGrid
# 按crash排序的值绘图,x_vars,y_vars表示x轴或者y轴
g = sns.PairGrid(crashes.sort_values("total", ascending=False),
x_vars=crashes.columns[:-3], y_vars=["abbrev"],
height=10, aspect=.25)
# Draw a dot plot using the stripplot function
g.map(sns.stripplot, size=10, orient="h",
palette="ch:s=1,r=-.1,h=1_r", linewidth=1, edgecolor="w")
# Use the same x axis limits on all columns and add better labels
# 设置x轴,x标签
g.set(xlim=(0, 25), xlabel="Crashes", ylabel="") # Use semantically meaningful titles for the columns
titles = ["Total crashes", "Speeding crashes", "Alcohol crashes",
"Not distracted crashes", "No previous crashes"] #去除轴线
for ax, title in zip(g.axes.flat, titles): # Set a different title for each axes
ax.set(title=title) # Make the grid horizontal instead of vertical
ax.xaxis.grid(False)
ax.yaxis.grid(True) sns.despine(left=True, bottom=True);

8. Plotting a three-way ANOVA(catplot)

# Load the example exercise dataset
df = sns.load_dataset("exercise") # Draw a pointplot to show pulse as a function of three categorical factors
# 分类型数据作坐标轴画图catplot,
# col表示用什么变量对图像在横坐标方向分列
# hue表示在单个维度上用某个变量区分;
# capsize表示延伸线的长度
g = sns.catplot(x="time", y="pulse", hue="kind", col="diet",
capsize=0.2, palette="YlGnBu_d", height=6, aspect=.75,
kind="point", data=df)
g.despine(left=True);

9. Linear regression with marginal distributions(jointplot)

sns.set(style="darkgrid")

tips = sns.load_dataset("tips")
# 设置联合图像,类型是"reg"回归图
g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
xlim=(0, 60), ylim=(0, 12), color="m", height=7)

10. Plotting model residuals(residplot)

sns.set(style="whitegrid")

# Make an example dataset with y ~ x
rs = np.random.RandomState(7)
x = rs.normal(2, 1, 75)
y = 2 + 1.5 * x + rs.normal(0, 2, 75) # Plot the residuals after fitting a linear model 残差图
# 中间曲线为残差曲线((对比一阶拟合直线的残差)),lowess曲线平滑
sns.residplot(x, y, lowess=True, color="g");

[seaborn] seaborn学习笔记11-绘图实例(3) Drawing example(3)的更多相关文章

  1. [seaborn] seaborn学习笔记12-绘图实例(4) Drawing example(4)

    文章目录 12 绘图实例(4) Drawing example(4) 1. Scatterplot with varying point sizes and hues(relplot) 2. Scat ...

  2. [seaborn] seaborn学习笔记10-绘图实例(2) Drawing example(2)

    文章目录 10 绘图实例(2) Drawing example(2) 1. Grouped violinplots with split violins(violinplot) 2. Annotate ...

  3. [seaborn] seaborn学习笔记9-绘图实例(1) Drawing example(1)

    文章目录 9 绘图实例(1) Drawing example(1) 1. Anscombe's quartet(lmplot) 2. Color palette choices(barplot) 3. ...

  4. 并发编程学习笔记(11)----FutureTask的使用及实现

    1. Future的使用 Future模式解决的问题是.在实际的运用场景中,可能某一个任务执行起来非常耗时,如果我们线程一直等着该任务执行完成再去执行其他的代码,就会损耗很大的性能,而Future接口 ...

  5. SpringMVC:学习笔记(11)——依赖注入与@Autowired

    SpringMVC:学习笔记(11)——依赖注入与@Autowired 使用@Autowired 从Spring2.5开始,它引入了一种全新的依赖注入方式,即通过@Autowired注解.这个注解允许 ...

  6. Spring 源码学习笔记11——Spring事务

    Spring 源码学习笔记11--Spring事务 Spring事务是基于Spring Aop的扩展 AOP的知识参见<Spring 源码学习笔记10--Spring AOP> 图片参考了 ...

  7. Ext.Net学习笔记11:Ext.Net GridPanel的用法

    Ext.Net学习笔记11:Ext.Net GridPanel的用法 GridPanel是用来显示数据的表格,与ASP.NET中的GridView类似. GridPanel用法 直接看代码: < ...

  8. SQL反模式学习笔记11 限定列的有效值

    目标:限定列的有效值,将一列的有效字段值约束在一个固定的集合中.类似于数据字典. 反模式:在列定义上指定可选值 1. 对某一列定义一个检查约束项,这个约束不允许往列中插入或者更新任何会导致约束失败的值 ...

  9. golang学习笔记11 golang要用jetbrain的golang这个IDE工具开发才好

    golang学习笔记11   golang要用jetbrain的golang这个IDE工具开发才好  jetbrain家的全套ide都很好用,一定要dark背景风格才装B   从File-->s ...

随机推荐

  1. 分布式存储系统之Ceph集群RadosGW基础使用

    前文我们了解了MDS扩展相关话题,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/16759585.html:今天我们来聊一聊RadosGW的基础使用相关话题: ...

  2. 使用MVC的实现登录注册功能

    文章目录 1.视图层(View)页面的编写: 1.1.登录页面 1.2.注册页面 2.控制层(Controller)的编写 2.1. 注册 2.2 .登录 2.3 .实体类 3.Model层(Mode ...

  3. 某OA系统需要提供一个假条审批的模块,如果员工请假天数小于3天,主任可以审批该请假条;如果员工请假天数大于等于3天,小于10天,经理可以审批;如果员工请假天数大于等于10天,小于30天,总经理可以审批

    某OA系统需要提供一个假条审批的模块,如果员工请假天数小于3天,主任可以审批该请假条:如果员工请假天数大于等于3天,小于10天,经理可以审批:如果员工请假天数大于等于10天,小于30天,总经理可以审批 ...

  4. 30.Serializers模块源码解析

    rest_framework序列化类的继承关系 field类: 序列化基类的基类 BaseSerializer: 继承field 派生ListSerializer序列化类 Serializer: 继承 ...

  5. settings.py 配置汇总

    数据库配置: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 数据库引擎 'NAME': ' ', #数据库名称 ...

  6. 三十一、kubernetes网络介绍

    Kubernetes 网络介绍 Service是Kubernetes的核心概念,通过创建Service,可以为一组具有相同功能的容器应用提供一个统一的入口地址,并且将请求负载分发到后端的各个容器应用上 ...

  7. 十、Pod的init containers

    Pod 的 init Containers Pod 我们可以分为两类,一种属于自主式 Pod ,还有一种属于控制器管理的 Pod . 一.Pod 的 initContainers 基本概念: ​Pod ...

  8. 「浙江理工大学ACM入队200题系列」问题 A: 零基础学C/C++34—— 3个数比较大小(冒泡排序与选择排序算法)

    本题是浙江理工大学ACM入队200题第四套中的A题,同时给出了冒泡排序和选择排序算法 我们先来看一下这题的题面. 由于是比较靠前的题目,这里插一句.各位新ACMer朋友们,请一定要养成仔细耐心看题的习 ...

  9. Linux内存泄露案例分析和内存管理分享

    作者:李遵举 一.问题 近期我们运维同事接到线上LB(负载均衡)服务内存报警,运维同事反馈说LB集群有部分机器的内存使用率超过80%,有的甚至超过90%,而且内存使用率还再不停的增长.接到内存报警的消 ...

  10. ENS框架下一次控制灯的调试记录

    正常流程 登录小站,点击管理--磁盘,在硬盘下创建分区并挂载 安全下电,拔掉硬盘和TEC,再上电 硬件端 drv_fault_check_init 初始化 并绑定硬件回调 drv_fault_chec ...