Search code examples
pythonmatplotlibplotwolfram-mathematicadensity-plot

How to use python imshow, for example, with the irregular data points?


Suppose I have a list of data points of the form (xi, yi, zi) and I want to plot a 2D density plot with it. In mathematica, you just call the function ListDensityPlot function. In python, it seems density plot is achieved by using imshow. However, it seems the required data should be in regular form. How to get the similar effect given the data sets?

Here is the mathematica code:

n = 100;
xs = RandomReal[1, n];
ys = RandomReal[1, n];
zs = xs + ys;
data = Table[{xs[[i]], ys[[i]], zs[[i]]}, {i, n}];
ListDensityPlot[data, PlotRange -> All, PlotLegends -> Automatic]

The effect of the above code is (of course, one can set the range to remove the white regions):

enter image description here

In python, I have generated the data, how to throw it into a function list_density_plot to achieve similar effects?

def f(x, y):
    return x+y

N = 100
xs = np.random.random(N)
ys = np.random.random(N)
zs = f(xs, ys)

data = [(xs[i], ys[i], zs[i]) for i in range(N)]
list_density_plot(data)  # ???

Solution

  • I think you are looking for plt.tricontourf or plt.tripcolor.

    Example with plt.tripcolor:

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    def f(x, y):
        return x + y
    
    
    N = 100
    xs = np.random.random(N)
    ys = np.random.random(N)
    zs = f(xs, ys)
    
    plt.tripcolor(xs, ys, zs)
    plt.show()
    

    enter image description here