0

Context:

  • 3x35 values array that associates 1 value per segment
  • 4x35x2 matpos array that gathers the coordinates of 4x35 points (hence 3x35 segments).

Question:

How can I define each segment's color based on their values from the values array ?

Code attempt:

# Array of values for each point
values = np.random.rand(3,35)

# Generate array of positions
x = np.arange(0,35)
y = np.arange(0,4)
matpos = np.array([[(y[i], x[j]) for j in range(0,len(x))] for i in range(0,len(y))])

# plot the figure
plt.figure()
for i in range(len(y)-1):
    for j in range(len(x)):

        # plot each segment
        plt.plot(matpos[i:i+2,j,0],matpos[i:i+2,j,1]) #color = values[i,j]

1 Answer 1

1

If your values are just along a grid, you might as well just use plt.imshow(values).

Updated code for desired result:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# Array of values for each point
values = np.random.rand(3,35)

# Transform value to colors depending on colormap
color_norm = mpl.colors.Normalize(np.min(values), np.max(values))

color_map = mpl.cm.get_cmap('viridis')

colors = color_map(color_norm(values))

plt.close('all')

plt.figure()

for (y, x), value in np.ndenumerate(values):

    
    plt.plot([x, x+1], [y, y], c = colors[y,x], linewidth = 10)
Sign up to request clarification or add additional context in comments.

5 Comments

I want them as lines because they are superimposed on a map
Ah, I see, and you want each line segment of each line to be colored according to your value?
Yes, exactly ! I know how to do that with scatterplot, but not with plot. And I couldn't find a way to plot segments with scatterplot.
This would require a bunch of Line2D segments, I believe.
@Nihilum, I've updated the answer for what you want. The main thing is learning to normalize your values to 0 to 1 for a colormap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.