Search code examples
pythonlistmatrixplothistogram

How to plot 2d histograms from a list of lists?


I have a 2d histogram which is logged and saved into a list of lists as below:

lst:
    [[1.0, 1.0, 10], [1.0, 2.0, 28.6], [1.0, 3.0, 26.93], [1.0, 4.0, 26.93],[2.0, 1, 6],[2.0, 2.0, 4],[2.0, 3.0, 67],[2.0, 4, 23],[3.0, 1.0, 12], [3.0, 2.0, 65], [3.0, 3.0, 33], [3.0, 4.0, 53]]

The first and second items refer to x and y, and the third one points to the value of that cell. I would like to plot them as a 2d heatmap. Any idea so I can plot them?


Solution

  • You need only transpose your list of lists and you can plot!

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = [[1.0, 1.0, 10], 
            [1.0, 2.0, 28.6], 
            [1.0, 3.0, 26.93], 
            [1.0, 4.0, 26.93],
            [2.0, 1, 6],
            [2.0, 2.0, 4],
            [2.0, 3.0, 67],
            [2.0, 4, 23],
            [3.0, 1.0, 12], 
            [3.0, 2.0, 65], 
            [3.0, 3.0, 33],
            [3.0, 4.0, 53]]
    
     data = np.array(data).T
    
     fig, axs = plt.subplots(2, 2, figsize=(5, 5))
     axs[0, 0].hist(data[0])
     axs[1, 0].scatter(data[0], data[1])
     axs[0, 1].plot(data[0], data[1])
     axs[1, 1].hist2d(data[0], data[1])
    
     plt.show()