Question

I am quite new with Python and even I have done pretty deep and long research I think I need a confirmation from community before opening a case on github.

I am plotting two "hinton plots" but I am using color range to represent matrix value.
Using subplot for some reason draws background of first plot in last subplot with first mymap color (blue in my case). If overwrites set_facecolor = 'gray' in any case (even if I am setting background color after plotting). Also I found that this bug accrues only if matrix values are greater than 0.
Please see pictures (and image descriptions) and code below.

Background of the first picture on the second subplot is blue. Background of the first picture on the second subplot is blue Third subplot added with no data, now it is blue colored and first square of second subplot is not. Third subplot added with no data, now it is blue colored and first square of second subplot is not

For first picture result change 6-th line to: fig, (axe_1, axe_2) = plt.subplots(1,2)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl


fig, (axe_1, axe_2, axe_3) = plt.subplots(1, 3)
my_min, my_max = (0, 10)
step = 1
mymap = mpl.colors.LinearSegmentedColormap.from_list("my list", ['blue','red'])
levels = range(my_min, my_max+step, step)
matrix = [None, None]
matrix[0] = np.asanyarray([[0, 1, 2], [3, 0, 5], [6, 7, 0]])
matrix[1] = np.asanyarray([[0, 9, 8], [7, 0, 6], [5, 4, 0]])

for iter, item in enumerate([axe_1, axe_2]):

    item.patch.set_facecolor('gray')
    item.set_aspect('equal', 'box')
    item.xaxis.set_major_locator(plt.NullLocator())
    item.yaxis.set_major_locator(plt.NullLocator())
    Z = [[0, 0], [0, 0]]
    CS3 = plt.contourf(Z, levels, cmap=mymap)
    for (x, y), z in np.ndenumerate(matrix[iter]):
        b = (float(z)-my_min)/(my_max-my_min)
        g = 0
        r = 1-b
        rect = plt.Rectangle([y, x], 0.9, 0.9, facecolor=(r, g, b), edgecolor="black")
        item.add_patch(rect)
    item.autoscale_view()
plt.show()

If I haven't made any stupid mistakes and you will confirm this is a bug I will open an issue on github.

Was it helpful?

Solution

The problem seems to be the call to plt.contourf (which I do not strictly understand why is there). But, it is being called through the state machine interface and hence both times through the loop plots to axe_2 (as that is what plt.gca() returns). You are plotting the contour of a 2x2 all 0 array, which it (correctly) draws as a blue box at [0, 0, 1, 1], which is the blue edge you see.

It works 'correctly' in the case of 3 axes as pyplot thinks the last axes is the current axes.

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