I generate a matplotlib 3d surface plot. I only need to see the upper-triangular half of the matrix on the plot, as the other half is redundant.
np.triu() makes the redundant half of the matrix zeros, but I'd prefer if I can make them Nans, then those cells don't show up at all on the surface plot.
What would be a pythonic way to fill with NaN instead of zeros? I cannot do a search-and-replace 0 with NaN, as zeros will appear in the legitimate data I want to display.
You can use numpy.tril_indices()
to assign the NaN
value to lower triangle, e.g.:
>>> import numpy as np
>>> m = np.triu(np.arange(0, 12, dtype=np.float).reshape(4,3))
>>> m
array([[ 0., 1., 2.],
[ 0., 4., 5.],
[ 0., 0., 8.],
[ 0., 0., 0.]])
>>> m[np.tril_indices(m.shape[0], -1)] = np.nan
>>> m
array([[ 0., 1., 2.],
[ nan, 4., 5.],
[ nan, nan, 8.],
[ nan, nan, nan]])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments