Skip to content
Advertisement

Generating Scatter Plot from a Matrix

I have a code that generates random matrices of 0’s and 1’s, and I’d like to convert these matrices into scatter plots, where the coordinate corresponds to the matrix row/column, and the color of the scatter point corresponds to the value (red if 0, blue if 1 for example).

I’ve been able to do this with matplotlib, but my use-case involves generating thousands of these images and matplotlib is quite slow for this purpose. For this reason I’ve been trying to use pyctgraph, but am running into some trouble.

Matplotlib code:

JavaScript

Pyctgraph code attempt:

JavaScript

The pyctgraph code runs but extremely slowly so I must be doing something wrong due to my unfamiliarity with the package. Thank you for any help!

EDIT: Just to clarify, the desired end product is a grid of solid dots, with whitespace separating them. The number of red dots needs to be 26, and the number of blue dots 24, in a randomly shuffled order.

Advertisement

Answer

I think using a nested loop and running plt.scatter inside the loop is where your program is wasting a lot of time. it’s best to only run plt.scatter once and instead pass a meshgrid of the (x,y) coordinates with the colors randomly shuffled.

For example, I can generate the same plot without any loops or conditionals and I only need to call plt.scatter once instead of 5×10 = 50 times (!) for every single point

JavaScript

enter image description here

I added some benchmarking to demonstrate the improvement in performance we’re looking at:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement