Matplotlib Scatter Plots

I ran into a problem while upgrading code from Python 2 to Python 3 that required me to downgrade matplotlib to version 2.2.3 in order to get the functionality in place (all tests were passing except for plotting). Once that dust settled, I attempted to individually upgrade to matplotlib==3.0.2 and ran into trouble with how scatter parses color sequences.

I had a lot of trouble finding a good solution online, but after sifting through a lot of forums and GitHub issues1, and trying many permutations of different syntaxes, I finally came around to a “clean” solution that passed the tests as they were written. The issue was that the color argument must match the type of the x and y inputs into scatter, which was not the case before.

The code I was working with formed x and y by indexing a 2-d np.array (call it data), and I found that using np.reshape as follows led to the easiest backwards-compatible solution:

# inds represents indices
x = data[inds, 0]
y = data[inds, 1]
c = colors[inds] # colors is passed to be height of some function that takes x and y as inputs.
plt.scatter(np.reshape(x,-1), 
            np.reshape(y,-1), 
            c=np.reshape(c,-1),
            cmap=color_map) # color_map defined elsewhere

If inds is length-1 or length-N, this syntax still works and respects the new requirements for coloring scatterplots.


  1. Places where the issue is mentioned or discussed: #12429, #10365 ^
Avatar
Michael Pilosov
An (applied) mathematician on a mission. Based in Denver, CO.
Next
Previous