Home > Blockchain >  How to remove NaN values from matshow 2D plot and format labels as percentages
How to remove NaN values from matshow 2D plot and format labels as percentages

Time:09-28

I am plotting some 2D array data as a map with a color scale and I have some NaN values that I don't want to show up. I need these values to show up as plain white squares and for the formatting to be in percentage style. Here is what I have so far:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

filename = "data.csv"

df = pd.read_csv(filename, header=None)

fig, ax = plt.subplots()
ax.matshow(df, cmap='bwr')

for (i, j), z in np.ndenumerate(df):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center',
            bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3'))

plt.show()

This is the data I have:

enter image description here

...and here is what I get out right now. This is almost exactly what I want, except for those NaN values and the percentage formatting.

enter image description here

Any help would be very much appreciated.

CodePudding user response:

  • Format the text string with an if-else block.
    • nan can only be checked with np.isnan
    • See enter image description here

  • Related