0

I have a dataframe containing a column with numpy arrays and another one with floats, like this:

arrays          | floats
------------------------
(1.2, 3.4, 5.6) |  4.5
(1.7, 4.4, 8.1) |  5.5

I want to plot each of the arrays in a single plot, but I need the lines to have a color that depends on the float associated to it.

So far, I have done this:

# Plot
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm

colormap = cm.jet
normalize = mcolors.Normalize(vmin=np.min(floats.values), vmax=np.max(floats.values))
s_map = cm.ScalarMappable(norm=normalize, cmap=colormap)

x_axis = np.linspace(0, 10, len(arrays.values[0]))

for arr, flt in in zip(arrays.values, floats.values):
   plt.plot(x_axis, arr)
plt.show()

I know that it is possible to pass a color: plt.plot(x_axis, arr, color='b'), but how can I use the s_map variable to do this depending on the value of the second column?

I read similar questions here, but none solved my problem.

6659081
  • 381
  • 7
  • 21
  • Related: [How to map number to color using matplotlib's colormap?](https://stackoverflow.com/questions/15140072/how-to-map-number-to-color-using-matplotlibs-colormap) ..[creating over 20 unique legend colors using matplotlib](https://stackoverflow.com/questions/8389636/creating-over-20-unique-legend-colors-using-matplotlib) .. – wwii Jun 03 '20 at 18:24

1 Answers1

1
df = pd.DataFrame({'arrays':[(1.2, 3.4, 5.6),(1.7, 4.4, 8.1)],'floats':[4.5,5.5]})

Use s_map.to_rgba with the float value for each array.

colormap = cm.jet
normalize = mcolors.Normalize(vmin=np.min(floats), vmax=np.max(floats))
s_map = cm.ScalarMappable(norm=normalize, cmap=colormap)

for arr, flt in zip(df.arrays.values, df.floats.values):
    plt.plot(arr,color=s_map.to_rgba(flt))
plt.show()
wwii
  • 23,232
  • 7
  • 37
  • 77