Matplotlib 3D scatter plot with marker color matching RGB values

I uploaded the image to a numpy array using mahotas.

import mahotas img = mahotas.imread('test.jpg') 

Each pixel in img is represented by an array of RGB values:

 img[1,1] = [254, 200, 189] 

I made a three-dimensional diagram of the scattering of R values ​​on one axis, G values ​​on the 2nd axis and B values ​​on the third axis. It's not a problem:

 fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') for i in range(1,img.shape[1]+1): xs = img[i,1][0] ys = img[i,1][1] zs = img[i,1][2] ax.scatter(xs, ys, zs, c='0.5', marker='o') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() 

(I'm just drawing the first column of the image at the moment).

How can I color each of the scatter points by the color of each pixel in the image? for example, I would like to color the dots by their RGB value, but I'm not sure if this is possible?

+6
source share
1 answer

Yes, you can do this, but you need to do this using a separate mechanism, except for the argument c . In short, use facecolors=rgb_array .


First of all, let me explain what is happening. Collection that scatter returns has two β€œsystems” (due to the lack of a better term) for setting colors.

If you use the argument c , you set the colors through the ScalarMappable system ScalarMappable "This indicates that colors should be controlled by applying a color scheme to a single variable. (This is the set_array method of everything that inherits from ScalarMappable .)

In addition to the ScalarMappable system, collection colors can be set independently. In this case, you should use facecolors kwarg.


As a quick example, these points will have random rgb colors:

 import matplotlib.pyplot as plt import numpy as np x, y = np.random.random((2, 10)) rgb = np.random.random((10, 3)) fig, ax = plt.subplots() ax.scatter(x, y, s=200, facecolors=rgb) plt.show() 

enter image description here

+11
source

Source: https://habr.com/ru/post/984584/


All Articles