Question

I would like to replicate something like this in Python. Anyone know if this is possible?

I'll have a 2D array as input and text lists of labels for rows and columns.

The 2D array values should be plotted in each cell, as below.

Colorplot of 2d array with text labels

Was it helpful?

Solution

Since no one has answered you, here is a good starting point:

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

z = np.random.rand(10, 10) # generate random data
nx, ny = z.shape
indx, indy = np.arange(nx), np.arange(ny)
x, y = np.meshgrid(indx, indy)

fig, ax = plt.subplots()
ax.imshow(z.T, interpolation="nearest", cmap=cm.YlGn) # plot grid values

for xval, yval in zip(x.flatten(), y.flatten()):
    zval = z[xval, yval]
    t = "%.1f%%"%(zval * 100,) # format value with 1 decimal point
    c = 'w' if zval > 0.75 else 'k' # if dark-green, change text color to white
    ax.text(xval, yval, t, color=c, va='center', ha='center')

xlabels = 'abcdefghij'
ylabels = '0123456789'
ax.set_xticks(indx+0.5) # offset x/y ticks so gridlines run on border of boxes
ax.set_yticks(indy+0.5)
ax.grid(ls='-', lw=2)

# the tick labels, if you want them centered need to be adjusted in 
# this special way.
for a, ind, labels in zip((ax.xaxis, ax.yaxis), (indx, indy), 
                          (xlabels, ylabels)):
    a.set_major_formatter(ticker.NullFormatter())
    a.set_minor_locator(ticker.FixedLocator(ind))
    a.set_minor_formatter(ticker.FixedFormatter(labels))

ax.xaxis.tick_top()

plt.show()

enter image description here

OTHER TIPS

Thanks to @Bill, here is the answer, gently modified from his link

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7,7))

min_val, max_val, diff = 0., 10., 1.

#imshow portion
N_points = (max_val - min_val) / diff

random.seed(42)
imshow_data = np.random.rand(N_points, N_points)
ax.imshow(imshow_data, interpolation='nearest', cmap="GnBu" )

#text portion
ind_array = np.arange(min_val, max_val, diff)
x, y = np.meshgrid(ind_array, ind_array)

# Write the text to correct positions
for x_val, y_val in zip(x.flatten(), y.flatten()):
    c = "{0:.2}".format(imshow_data[y_val, x_val])
    ax.text(x_val, y_val, c, va='center', ha='center')


#set tick marks for grid
ax.set_xticks(np.arange(min_val-diff/2, max_val-diff/2))
ax.set_yticks(np.arange(min_val-diff/2, max_val-diff/2))

ax.set_xticks(np.arange(max_val))
ax.set_yticks(np.arange(max_val))

ax.set_xlim(min_val-diff/2, max_val-diff/2)
ax.set_ylim(min_val-diff/2, max_val-diff/2)

ax.grid()
plt.show()

This gives:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top