How to plot a heatmap from pandas DataFrame

前端 未结 1 1155
天涯浪人
天涯浪人 2020-12-30 16:54

Here is my dataframe:

              jan          f            m        a        m         j  \\
2000    -7.894737  22.387006    22.077922  14.5455  15.8038           


        
相关标签:
1条回答
  • 2020-12-30 17:25

    That is straightforward using seaborn; I demonstrate how to do it using random data, so all you have to do is to replace data in the example below by your actual dataframe.

    My dataframe looks like this:

                 A         B         C         D         E
    2000  0.722553  0.948447  0.598707  0.656252  0.618292
    2001  0.920532  0.054941  0.909858  0.721002  0.222167
    2002  0.048496  0.963871  0.689730  0.697573  0.349308
    2003  0.692897  0.272768  0.581736  0.150674  0.861672
    2004  0.889694  0.658286  0.879855  0.739821  0.010971
    2005  0.937347  0.132955  0.704528  0.443084  0.552123
    2006  0.869499  0.750177  0.675160  0.873720  0.270204
    2007  0.156933  0.186630  0.371993  0.153790  0.397232
    2008  0.384696  0.585156  0.746883  0.185457  0.095387
    2009  0.667236  0.340058  0.446081  0.863402  0.227776
    2010  0.817394  0.343427  0.804157  0.245394  0.850774
    

    The output then looks as follows (please note that the index is at the x-axis and the column names at the y-axis as requested):

    Here is the entire code with some inline comments:

    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    
    # create some random data; replace that by your actual dataset
    data = pd.DataFrame(np.random.rand(11, 5), columns=['A', 'B', 'C', 'D', 'E'], index = range(2000, 2011, 1))
    
    # plot heatmap
    ax = sns.heatmap(data.T)
    
    # turn the axis label
    for item in ax.get_yticklabels():
        item.set_rotation(0)
    
    for item in ax.get_xticklabels():
        item.set_rotation(90)
    
    # save figure
    plt.savefig('seabornPandas.png', dpi=100)
    plt.show()
    
    0 讨论(0)
提交回复
热议问题