8 避免过度绘图Avoid Overplotting(代码下载)

过度绘图是散点图及几天常见图表中最常见的问题之一。如下图所示当数据集很大时,散点图的点会重叠,使得图形变得不可读。在这篇文章中,提出了多种方法避免过度绘图。该章节主要内容有:

  1. 减小点的大小 reduce the dot size
  2. 使用透明度 use transparency
  3. 使用二维密度图 2D density graph
  4. 数据采样 Sample data
  5. 特定数据显示 Show a specific group
  6. 分组显示 Show putative structure
  7. 多图显示 faceting
  8. 数据分离 jitter
  9. 3D显示 3D image plot
  10. 边际图 Marginal distribution plot
# libraries and data
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd # Dataset:
df=pd.DataFrame({'x': np.random.normal(10, 1.2, 20000), 'y': np.random.normal(10, 1.2, 20000), 'group': np.repeat('A',20000) })
tmp1=pd.DataFrame({'x': np.random.normal(14.5, 1.2, 20000), 'y': np.random.normal(14.5, 1.2, 20000), 'group': np.repeat('B',20000) })
tmp2=pd.DataFrame({'x': np.random.normal(9.5, 1.5, 20000), 'y': np.random.normal(15.5, 1.5, 20000), 'group': np.repeat('C',20000) })
df=df.append(tmp1).append(tmp2) # plot
sns.regplot(x='x', y='y', data=df, marker='o',fit_reg=False)
plt.xlabel('Value of X');
plt.ylabel('Value of Y');
plt.title('Overplotting looks like that:', loc='left');

1. 减小点的大小 reduce the dot size

# Plot with small marker size scatter_kws控制点的大小
sns.regplot(x='x', y='y', data=df, marker='o',fit_reg=False, scatter_kws={"s":0.01})
plt.xlabel('Value of X')
plt.ylabel('Value of Y')
plt.title('Overplotting? Try to reduce the dot size', loc='left');

2. 使用透明度 use transparency

# Plot with transparency
sns.regplot(x='x', y='y', data=df, marker='o',fit_reg=False, scatter_kws={"color":"purple","alpha":0.5,"s":0.1}) # Titles
plt.xlabel('Value of X')
plt.ylabel('Value of Y')
plt.title('Overplotting? Try to use transparency', loc='left');

3. 使用二维密度图 2D density graph

# 2D density plot, kdeplot调用二维密度函数
sns.kdeplot(df.x, df.y, cmap="Reds", shade=True)
plt.title('Overplotting? Try 2D density graph', loc='left');
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. 数据采样 Sample data

# Sample 1000 random lines 随机获得1000个点
df_sample=df.sample(1000) # plot
sns.regplot(x='x', y='y', data=df_sample, marker='o',fit_reg=False)
plt.xlabel('Value of X');
plt.ylabel('Value of Y');
plt.title('Overplotting? Sample data', loc='left');

5. 特定数据显示 Show a specific group

# Filter the data randomly 筛选数据
df_filtered = df[ df['group'] == 'A']
# 基于matplotlib绘制主要显示的类别数据
# Plot the whole dataset
plt.plot( df['x'], df['y'], linestyle='', marker='o', markersize=1.5, color="grey", alpha=0.3, label='other group')
# Add the group to study
plt.plot( df_filtered['x'], df_filtered['y'], linestyle='', marker='o', markersize=1.5, alpha=0.3, label='group A') # Add titles and legend
plt.legend(markerscale=8)
plt.xlabel('Value of X')
plt.ylabel('Value of Y')
plt.title('Overplotting? Show a specific group', loc='left');

6. 分组显示 Show putative structure

# Plot 不同组显示不同的颜色
sns.lmplot( x="x", y="y", data=df, fit_reg=False, hue='group', legend=False, palette="Accent", scatter_kws={"alpha":0.1,"s":15} ) # Legend
plt.legend(loc='lower right', markerscale=2) # titles
plt.xlabel('Value of X')
plt.ylabel('Value of Y')
plt.title('Overplotting? Show putative structure', loc='left');

7. 多图显示 faceting

# Use seaborn for easy faceting
# 应用多绘图网格函数FacetGrid实例化group,其中根据col="group"分组。
g = sns.FacetGrid(df, col="group", hue="group")
g = (g.map(plt.scatter, "x", "y", edgecolor="w"))

8. 数据分离 jitter

# Dataset:
a=np.concatenate([np.random.normal(2, 4, 1000), np.random.normal(4, 4, 1000), np.random.normal(1, 2, 500), np.random.normal(10, 2, 500), np.random.normal(8, 4, 1000), np.random.normal(10, 4, 1000)])
df=pd.DataFrame({'x': np.repeat( range(1,6), 1000), 'y': a }) # plot
sns.regplot(x='x', y='y', data=df, marker='o',fit_reg=False);

# A scatterplot with jitter
sns.stripplot(df.x, df.y, jitter=0.2, size=2)
plt.title('Overplotting? Use jitter when x data are not really continuous', loc='left');

9. 3D显示 3D image plot

# libraries
from scipy.stats import kde
from mpl_toolkits.mplot3d import Axes3D # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents
nbins=300
k = kde.gaussian_kde([df.x,df.y])
xi, yi = np.mgrid[ df.x.min():df.x.max():nbins*1j, df.y.min():df.y.max():nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()])) # Transform it in a dataframe
data=pd.DataFrame({'x': xi.flatten(), 'y': yi.flatten(), 'z': zi }) # Make the plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(data.x, data.y, data.z, cmap=plt.cm.Spectral, linewidth=0.2)
# Adapt angle, first number is up/down, second number is right/left
ax.view_init(30, 80)

10. 边际图 Marginal distribution plot

# 2D density + marginal distribution:
sns.jointplot(x=df.x, y=df.y, kind='kde');

[seaborn] seaborn学习笔记8-避免过度绘图Avoid Overplotting的更多相关文章

  1. Android学习笔记_点九绘图与软键盘和事件传递

    最近项目里遇到的几个小问题,以前只是用吗没有深入看过,现在总结到一起,防止以后这种小问题占用太多时间.还是通过网上别人总结的很多博客学习了,挑选出最易懂明了的. 还有leader很小的问题都不放过,亲 ...

  2. R语言学习笔记(五)绘图(1)

      R是一个惊艳的图形构建平台,这也是R语言的强大之处.本文将分享R语言简单的绘图命令.   本文所使用的数据或者来自R语言自带的数据(mtcars)或者自行创建.   首先,让我们来看一个简单例子: ...

  3. 吴裕雄--天生自然python学习笔记:Matplotlib 基本绘图

    使用 Matplotlib 组件绘图时,经常要与 Numpy 组件搭配使用 . 使用 Matplotlib 绘图首先要导入 Matplotlib 组件 , 由于大部分绘图功能是在 matplotlib ...

  4. 吴裕雄--天生自然 python开发学习笔记:一劳永逸解决绘图出现中文乱码问题方法

    import numpy as np import matplotlib.pyplot as plt x = np.random.randint(0,20,10) y = np.random.rand ...

  5. [seaborn] seaborn学习笔记0-seaborn学习笔记章节

    seaborn学习笔记章节 seaborn是一个基于matplotlib的Python数据可视化库.seaborn是matplotlib的高级封装,可以绘制有吸引力且信息丰富的统计图形.相对于matp ...

  6. webgl学习笔记二-绘图多点

    写在前面 建议先看下第一篇webgl学习笔记一-绘图单点 第一篇文章,介绍了如何用webgl绘图一个点.接下来本文介绍的是如何绘制多个点.形成一个面. webgl提供了一种很方便的机制,即缓冲区对象, ...

  7. matlab学习笔记9 高级绘图命令_2 图形的高级控制_视点控制和图形旋转_色图和颜色映像_光照和着色

    一起来学matlab-matlab学习笔记9 高级绘图命令_2 图形的高级控制_视点控制和图形旋转_色图和颜色映像_光照和着色 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考书籍 < ...

  8. matlab学习笔记9 高级绘图命令_1 图形对象_根对象,轴对象,用户控制对象,用户菜单对象

    一起来学matlab-matlab学习笔记9 高级绘图命令_1 图形对象_根对象,轴对象,用户控制对象,用户菜单对象 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考书籍 <matl ...

  9. matlab学习笔记8 基本绘图命令-三维绘图

    一起来学matlab-matlab学习笔记8 基本绘图命令_6 三维绘图 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考书籍 <matlab 程序设计与综合应用>张德丰等著 ...

随机推荐

  1. BLS签名算法

    前言 [失踪人口回归 (*/ω\*)] 真的好久好久没有更新了,因为自己也还在找方向,但还是把新学的知识记录在博客里.今天要介绍的是BLS签名算法. 一.BLS签名算法简介 BLS签名算法[1]是由斯 ...

  2. Filter 筛选器(二)之 ExceptionFilter

    public class MyExceptionFilter : IAsyncExceptionFilter { private readonly ILogger<MyExceptionFilt ...

  3. 详解商业智能“前世今生”,“嵌入式BI”到底是如何产生的?

    嵌入式分析是使任何应用程序或用户更容易获得数据分析和商业智能的技术. 商业智能是通过分析业务数据辅助决策获取数据背后的 0信息. 商业智能软件和技术包含了报表查询,OLAP,数据挖掘及高级数据分析,最 ...

  4. 华为路由器vrrp(虚拟路由器冗余协议)基本配置命令

    vrrp(虚拟路由器冗余协议)基本配置 int g0/0/0 vrrp vrid 1 virtual-ip 172.16.1.254 创建VRRP备份组,备份组号为1,配置虚拟IP为172.16.1. ...

  5. day01-4-订座功能

    满汉楼01-4 4.功能实现03 4.5订座功能 4.5.1功能说明 如果该餐桌处于已经预定或者就餐状态时,不能进行预定,并给出相应提示 4.5.2思路分析 根据显示界面,要考虑以下两种状态 检测餐桌 ...

  6. 虚拟机VMware运行Ubuntu时无法和主机之间复制粘贴的问题

    解决虚拟机VMware运行Ubuntu时无法和主机之间复制粘贴的问题 执行以下命令并重启即可解决 sudo apt-get autoremove open-vm-tools sudo apt-get ...

  7. Aspose.Cell和NPOI生成Excel文件

    1.使用Aspose.Cell生成Excel文件,Aspose.Cell是.NET组件控件,不依赖COM组件 1首先一点需要使用新建好的空Excel文件做模板,否则容易产生一个多出的警告Sheet 1 ...

  8. Codeforces Round #802 (Div. 2)C. Helping the Nature(差分)

    题目链接 题目大意: 给你一个有n个元素的数组a,你可以通过一下三种操作使数组的每一个值都为0: 选择一个下标i,然后让a[1],a[2]....a[ i ] 都减一; 选择一个下标i,然后让a[i] ...

  9. 搜索"xxxx"的进程,同时杀进程

    一.搜索"xxxx"的进程,同时杀进程,命令如下: ps -ef|grep xxxx|grep -v 'grep'|awk '{print $2}'|xargs kill -9 命 ...

  10. 【题解】CF356A Knight Tournament

    题面传送门 本蒟蒻想练习一下并查集,所以是找并查集标签来这里的.写题解加深理解. 解决思路 自然,看到区间修改之类很容易想到线段树,但本蒟蒻线段树会写挂,所以这里就讲比较简单的并查集思路. 并查集的核 ...