Making heatmap from pandas DataFrame Making heatmap from pandas DataFrame python python

Making heatmap from pandas DataFrame


For people looking at this today, I would recommend the Seaborn heatmap() as documented here.

The example above would be done as follows:

import numpy as np from pandas import DataFrameimport seaborn as sns%matplotlib inlineIndex= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']Cols = ['A', 'B', 'C', 'D']df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)sns.heatmap(df, annot=True)

Where %matplotlib is an IPython magic function for those unfamiliar.


If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient() method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:

import numpy as np import pandas as pdindex= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']cols = ['A', 'B', 'C', 'D']df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)df.style.background_gradient(cmap='Blues')

enter image description here

For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.


You want matplotlib.pcolor:

import numpy as np from pandas import DataFrameimport matplotlib.pyplot as pltindex = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']columns = ['A', 'B', 'C', 'D']df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)plt.pcolor(df)plt.yticks(np.arange(0.5, len(df.index), 1), df.index)plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)plt.show()

This gives:

Output sample