Is it possible to annotate imshow heatmap the way that if the value from pandas Dataframe is e.g. less than 3, then make mark “x” in that specific heatmap window?
Lets assume I have similar data to this example:
d = {'col1': [1,2,1,5,3], 'col2': [3,4,1,5,2],'col3': [3,4,3,1,2],'col4': [3,4,1,2,5]} df = pd.DataFrame(data=d) fig = plt.figure(figsize=(6,4)) plot = plt.imshow(df) ax = plot.axes ax.invert_yaxis() ax.set_xticklabels(df.columns)
I saw that we can annotate all heatmap windows with corresponding values, however I can’t figure out how to annotate just the windows below my given limit and not with the corresponding value but e.g. with mark “x”. Can I ask for suggestions if it is possible with matplotlib heatmaps, please? Thank you.
Advertisement
Answer
- Iterate through the values, and use an
if-condition
to control adding the text. - Modified from how to annotate heatmap with text in matplotlib
d = {'col1': [1,2,1,5,3], 'col2': [3,4,1,5,2],'col3': [3,4,3,1,2],'col4': [3,4,1,2,5]} df = pd.DataFrame(data=d) fig = plt.figure(figsize=(7, 7)) plot = plt.imshow(df) ax = plot.axes ax.invert_yaxis() ax.set_xticks(range(len(df.columns)), df.columns) for y in range(df.shape[0]): for x in range(df.shape[1]): val = df.iloc[y, x] if val >= 3: val = 'x' plt.text(x, y, val, fontsize=14, horizontalalignment='center', verticalalignment='center')