绘制无缝分发的推文

时间:2015-11-22 12:06:15

标签: python matplotlib

我现在收集了来自Twitter的推文,我试图在地理上绘制推文的分布。为此,我将整个方形区域划分为小方块,并计算每个方块中的推文数量。最后,我使用matplotlib绘制下图:

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha=0.3, cmap='Accent')

enter image description here

问题是高程图不平滑。我想要一种从数据中绘制平滑曲线的方法。 2D中的一个示例是当我们有图像的直方图时,我们可以在分布上绘制平滑曲线,如下所示: enter image description here

所以我的问题是有没有办法从离散数据中绘制光滑的表面?

1 个答案:

答案 0 :(得分:1)

扩展我的答案,以下是重新取样和平滑(gaussian_filter())/样条插值(RectBivariateSpline)的结果。请注意,提供一个用于绘制图表的模板代码会很高兴,但是由于你没有,我不得不即兴发挥。

import numpy

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def plot(name, method):
    numpy.random.seed(123)

    x = numpy.linspace(0, 50, 51)
    X, Y = numpy.meshgrid(x, x)
    Z = numpy.zeros((x.size, x.size))

    for n in range(50):
        i = numpy.random.randint(0, x.size)
        j = numpy.random.randint(0, x.size)
        Z[i, j] = numpy.abs(numpy.random.normal()) * 1000

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    if method == 0:
    # regular plot
        ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha=0.3, cmap='Accent')

    else:
        # create a finer grid
        resample_coeff = 2
        Z2 = numpy.repeat(Z, resample_coeff, 0).repeat(resample_coeff, 1)
        x2 = numpy.linspace(x[0], x[-1], x.size * resample_coeff)
        X2, Y2 = numpy.meshgrid(x2, x2)

        if method == 1:
        # smoothing
            from scipy.ndimage.filters import gaussian_filter
            Z2 = gaussian_filter(Z2, 1)

        elif method == 2:
        # interpolation
            from scipy.interpolate import RectBivariateSpline
            spline = RectBivariateSpline(
                x, x, Z, bbox=[x[0], x[-1], x[0], x[-1]])
            Z2 = spline.ev(X2, Y2)

        ax.plot_surface(X2, Y2, Z2, rstride=1, cstride=1, alpha=0.3, cmap='Accent')

    fig.savefig(name)

if __name__ == '__main__':
    plot('t0.png', 0)
    plot('t1.png', 1)
    plot('t2.png', 2)

初始图表: initial graph

平滑: Smoothing

插值(注意负区域;你的多项式插值): Interpolation