mercredi 21 juillet 2021

How to randomly select colors in plotly python graph

I have the following data lists:

date = ['2019-01-01', '2019-01-18', '2019-02-03']
value1 = [6798.0, 436.0, 348.0]
value2 = [500.0, 455.0, 348.0]

From these lists I generate a line graph using the plotly library, this way:

  trace_1 = go.Scatter(x = date, 
                       y = value1,
                       mode = 'markers+lines',
                       marker_color='rgb(152, 0, .8)',      
                      name = '1')

  trace_2 = go.Scatter(x = date, 
                       y = value2,
                       mode = 'markers+lines',
                       marker_color='rgb(0, 0, .8)',
                       name = '2')

  data_total = [trace_1, trace_2]

  fig = go.Figure(data=data_total, layout=layout)
  py.iplot(fig)

The graphic is working perfectly and the lines are in different colors. However, I would like the line colors, instead of manual as I did, to be automatically generated randomly.

Following this tutorial: https://www.kite.com/python/answers/how-to-generate-random-colors-in-matplotlib-in-python

I tried to do:

  colors = np.random.rand(1,3)

  trace_1 = go.Scatter(x = date, 
                       y = value1,
                       mode = 'markers+lines',
                       marker_color = colors,
                       name = '1')

   trace_2 = go.Scatter(x = date, 
                        y = value2,
                        mode = 'markers+lines',
                        marker_color = colors,
                        name = '2')

  data_total = [trace_1, trace_2]

  fig = go.Figure(data=data_total, layout=layout)
  py.iplot(fig)

But this code doesn't work.




Aucun commentaire:

Enregistrer un commentaire