Search code examples
pythonplotlymesh

random colours for each block in a 3D plot Matplotlib


I am trying to assign a random colour to each block in my 3D plot. The code below is in a for loop and the boxes are printing, but they are all gray.

blockcolor = [f'rgb(np.random.randint(0,256))']
        mesh.append(go.Mesh3d(x=X, y=Y, z=Z, i=I, j=J, k=K,facecolor= blockcolor, flatshading=True))

Here is the output: Anyone have know what's wrong or have a better way. I realise I didn't add much code I can if necessary I'm just quite sure the problem is here.

Note: I have tried a random hexadecimal generator but it gives the same result.enter image description here


Solution

  • I see at least two issues:

    1. You need accolades to make the numpy random function work inside the string

      f'rgb({np.random.randint(0,256)})'

    2. This only creates a single number, which will always be a shade of grey. You need to generate random triplets for RGB

      f'rgb({[np.random.randint(0,256) for _ in range(3)]})'