2

I'm trying a create a plot with two types of plots on top of each other: pyplot.spy over pyplot.imshow. Since spy plots a sparse matrix, I want it to be transparent where the matrix has zeros. However, when I plot the sparse matrix on the same axis, it seems to be creating a new canvas covering the one created by imshow.

Here's a description of my steps. Note that I'm using spy in the marker style, which returns a Line2D object.

A: array of size m*n

B: array of size m*n where most elements are 0s(rest are 1s)

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
p1 = ax.imshow(A, aspect='auto')
p2 = ax.spy(B, aspect = 'auto', markersize=2, alpha = 0.25)
plt.show()

I'd appreciate suggestions and help.

Karen Chen
  • 21
  • 3

1 Answers1

0

Building upon the idea in: https://stackoverflow.com/a/51601850/8447885 and adapting it a bit for your needs, you can modify the color map such that the alpha channel is set to 0 for the first value (or similarly to the cited link above – gradually increases from 0 to 1), and use this colormap with modified alpha values for your second plot:

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

A = np.random.rand(5,4)
B = np.zeros((5,4))
B[2,2] = 1
B[3,2] = 1
B[4,2] = 1
color_array = plt.get_cmap('seismic')(range(256))
color_array[:,-1] = np.linspace(0,1,256) # the alpha channel is the last one in the array
map_object = LinearSegmentedColormap.from_list(name='seismic_alpha',colors=color_array)
plt.register_cmap(cmap=map_object)

fig, ax = plt.subplots()
p1 = ax.imshow(A, aspect='auto',cmap='seismic')
p2 = ax.spy(B, aspect = 'auto', alpha = 0.75, cmap='seismic_alpha')
plt.show()
BossaNova
  • 1,509
  • 1
  • 13
  • 17
  • Thanks for your help. I should've mentioned I'm using spy in the marker style, which returns a Line2D object rather than an image. Your solution works for the image style I believe, but I got some inspiration.... – Karen Chen Jul 02 '20 at 22:21