我怎样才能绘制出大约2000万点的散点图?

2024-10-03 17:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用matplotlib创建一个散点图,它由大约2000万个数据点组成。即使在将alpha值设置为最低值之后,最终没有任何可见数据,结果也只是一个完全黑色的图。在

plt.scatter(timedPlotData, plotData, alpha=0.01, marker='.')

x轴是大约2个月的连续时间轴,y轴由150k个连续整数值组成。在

有没有办法画出所有的点,这样它们随时间的分布仍然可见?在

谢谢你的帮助。在


Tags: 数据alphamatplotlib时间plt整数marker黑色
3条回答

我的建议是在绘制原始数据之前对其使用排序和移动平均算法。这将使平均值和趋势在关注的时间段内保持不变,同时减少图上的混乱。在

有不止一种方法可以做到这一点。很多人建议使用热图/核密度估计/2d直方图。@巴基建议使用移动平均线。此外,您可以在移动的最小值和移动的最大值之间填充,并在顶部绘制移动平均值。我经常叫它“chunkplot”,但那是个很糟糕的名字。下面的实现假设您的时间(x)值是单调增加的。如果不是,那么在chunkplot函数中的“chunking”之前按xy排序就足够简单了。在

这里有几个不同的想法。哪一个最好取决于你想在情节中强调什么。请注意,这将是相当缓慢的运行,但这主要是由于分散图。其他打印样式的速度要快得多。在

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
np.random.seed(1977)

def main():
    x, y = generate_data()
    fig, axes = plt.subplots(nrows=3, sharex=True)
    for ax in axes.flat:
        ax.xaxis_date()
    fig.autofmt_xdate()

    axes[0].set_title('Scatterplot of all data')
    axes[0].scatter(x, y, marker='.')

    axes[1].set_title('"Chunk" plot of data')
    chunkplot(x, y, chunksize=1000, ax=axes[1],
              edgecolor='none', alpha=0.5, color='gray')

    axes[2].set_title('Hexbin plot of data')
    axes[2].hexbin(x, y)

    plt.show()

def generate_data():
    # Generate a very noisy but interesting timeseries
    x = mdates.drange(dt.datetime(2010, 1, 1), dt.datetime(2013, 9, 1),
                      dt.timedelta(minutes=10))
    num = x.size
    y = np.random.random(num) - 0.5
    y.cumsum(out=y)
    y += 0.5 * y.max() * np.random.random(num)
    return x, y

def chunkplot(x, y, chunksize, ax=None, line_kwargs=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    if line_kwargs is None:
        line_kwargs = {}
    # Wrap the array into a 2D array of chunks, truncating the last chunk if
    # chunksize isn't an even divisor of the total size.
    # (This part won't use _any_ additional memory)
    numchunks = y.size // chunksize
    ychunks = y[:chunksize*numchunks].reshape((-1, chunksize))
    xchunks = x[:chunksize*numchunks].reshape((-1, chunksize))

    # Calculate the max, min, and means of chunksize-element chunks...
    max_env = ychunks.max(axis=1)
    min_env = ychunks.min(axis=1)
    ycenters = ychunks.mean(axis=1)
    xcenters = xchunks.mean(axis=1)

    # Now plot the bounds and the mean...
    fill = ax.fill_between(xcenters, min_env, max_env, **kwargs)
    line = ax.plot(xcenters, ycenters, **line_kwargs)[0]
    return fill, line

main()

enter image description here

对于每一天,统计每个值的频率(a集合。计数器会很好地完成这项工作),然后绘制一张热图,每天一张。对于发布,请使用灰度作为热图颜色。在

相关问题 更多 >