【问题标题】:How to collapse 2D scatter plot into a dot plot?如何将二维散点图折叠成点图?
【发布时间】:2020-09-21 16:49:44
【问题描述】:

我有一个非常大的形状为 (186295, 2) 的二维数组,其中每个 2 元素子数组的第一个元素是 x,第二个元素是 y。以下是我通过在matplotlib 中分离 x 和 y 分量来生成散点图的方法:

ax.scatter(A[:, 0]+np.random.uniform(-.02, .02, A.shape[0]), A[:, 1], s=2, color='b', alpha=0.5, zorder=3)

但是,我想要

x 值在 [8,9.2] 范围内的所有点在中点显示为点图x=8.6,

x 值在 [9.2,10.4] 范围内的所有点都显示为中点处的点图 x=9.8,

x 值在 [10.4,12.2] 范围内的所有点在中点显示为点图x=11.3

非常感谢您的帮助,

【问题讨论】:

    标签: arrays python-3.x numpy scatter-plot scatter


    【解决方案1】:

    你可以使用np.select:

    例子:

    import numpy as np
    from matplotlib import pyplot as plt
    
    n=100
    x = np.random.uniform(8, 12, n)
    y = np.random.uniform(.01, 1, n)
    a = np.array(list(zip(x,y)))
    
    
    fig,ax = plt.subplots(2, sharex=True)
    ax[0].scatter(a[:,0], a[:,1])
    ax[0].title.set_text('Scatter Plot')
    
    conditions = [a[:,0]<=8, a[:,0]<=9.2, a[:,0]<=10.4, a[:,0]<=12.2, a[:,0]>12.2]
    choices = [a[:,0], 8.6, 9.8, 11.3, a[:,0]]
    a[:,0] = np.select(conditions, choices)
    
    ax[1].scatter(a[:,0], a[:,1])
    ax[1].title.set_text('Dot Plot')
    

    结果:

    另一种可能性是使用np.digitize,因为它使用箱列表(上限)而不是条件列表,因此可以节省一些输入。

    【讨论】:

    • 谢谢你,我从来没有想过这个,
    • 既然我们知道所有东西在 [8,12.2] 之间都有 x 值,为什么我们不将条件定义为 8
    • 在这种特殊情况下你可以这样做,但在一般情况下,如果你有超出定义间隔的值,那么它们将被设置为零(除非你将默认值作为第三个参数传递给 np.选择)
    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多