4

I have a 1D array arr1d = ['A', 'B', 'C', 'D'] and I have a 2D array

arr2d =[[1, 2, 5, 3], [2, 1, 2, 5], [5, 3, 4, 4], [5, 5, 3, 4]] (say) I wish to plot the array using matplotlib (or any other library) in such a way that the output is in the following manner. I want the x and y axis to get labelled as per the 1D array as shown in the picture. How to achieve that?

enter image description here

2 Answers 2

3

You could try something like this:

from matplotlib import pyplot as plt
from matplotlib import colors
import numpy as np

arr1d = ['A', 'B', 'C', 'D']
data = np.array([[1, 2, 5, 3], [2, 1, 2, 5], [5, 3, 4, 4], [5, 5, 3, 4]])
cmap = colors.ListedColormap(['blue','red', 'green', 'yellow', 'cyan'])
fig, ax = plt.subplots()
ax.imshow(data, cmap=cmap)

for (i, j), z in np.ndenumerate(data):
    ax.text(j, i, '{}'.format(z), ha='center', va='center', size=12)
    
plt.xticks(np.arange(len(arr1d)), arr1d)
plt.yticks(np.arange(len(arr1d)), arr1d)
plt.show()

enter image description here

Using ListedColormap, you can decide which number is mapped to which color.

Or with grid lines:

from matplotlib import pyplot as plt
from matplotlib import colors
import numpy as np
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

arr1d = ['A', 'B', 'C', 'D']
data = np.array([[1, 2, 5, 3], [2, 1, 2, 5], [5, 3, 4, 4], [5, 5, 3, 4]])
cmap = colors.ListedColormap(['blue','red', 'green', 'yellow', 'cyan'])

_, ax = plt.subplots()
for (i, j), z in np.ndenumerate(data):
  ax.annotate('{}'.format(z), xy = (j + 0.4, i + 0.6), fontsize=15)

ax.imshow(data, cmap=cmap, extent=(0, data.shape[0], data.shape[1], 0))
ax.grid(color='black', linewidth=3)

plt.xticks(np.arange(len(arr1d)), arr1d)
plt.yticks(np.arange(len(arr1d)), arr1d)
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You could achieve a result close to what you need with matshow in matplotlib.

import matplotlib.pyplot as plt
arr1d = ['A', 'B', 'C', 'D']
arr2d =[[1, 2, 5, 3], [2, 1, 2, 5], [5, 3, 4, 4], [5, 5, 3, 4]]
plt.matshow(arr2d)
plt.xticks([0,1,2,3], arr1d)
plt.yticks([0,1,2,3], arr1d)
plt.show()

result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.