How to plot a density map in python?

后端 未结 2 871
囚心锁ツ
囚心锁ツ 2020-12-14 01:52

I have a .txt file containing the x,y values of regularly spaced points in a 2D map, the 3rd coordinate being the density at that point.

4.882812500000000E-0         


        
相关标签:
2条回答
  • 2020-12-14 02:10

    Here is my aim at a more complete answer including choosing the color map and a logarithmic normalization of the color axis.

    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    from matplotlib.colors import LogNorm
    import numpy as np
    x, y, z = np.loadtxt('data.txt', unpack=True)
    N = int(len(z)**.5)
    z = z.reshape(N, N)
    plt.imshow(z+10, extent=(np.amin(x), np.amax(x), np.amin(y), np.amax(y)),
            cmap=cm.hot, norm=LogNorm())
    plt.colorbar()
    plt.show()
    

    I assume here that your data can be transformed into a 2d array by a simple reshape. If this is not the case than you need to work a bit harder on getting the data in this form. Using imshow and not pcolormesh is more efficient here if you data lies on a grid (as it seems to do). The above code snippet results in the following image, that comes pretty close to what you wanted:

    Resulting image

    0 讨论(0)
  • 2020-12-14 02:11

    The comment from @HYRY is good, but a complete minimal working answer (with a picture!) is better. Using plt.pcolormesh

    import pylab as plt
    import numpy as np
    
    # Sample data
    side = np.linspace(-2,2,15)
    X,Y = np.meshgrid(side,side)
    Z = np.exp(-((X-1)**2+Y**2))
    
    # Plot the density map using nearest-neighbor interpolation
    plt.pcolormesh(X,Y,Z)
    plt.show()
    

    enter image description here

    If the data looks like your sample, numpy can load it using the command numpy.genfromtext.

    0 讨论(0)
提交回复
热议问题