Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: Define colours for a pie graph - (using low-level API)

So I got this code to make a pie chart, but I wanted to changes the colors of each class to the colors listed in the colors variable. The documentation about formatting plots in json is really hard to find so I can't figure it out. Does anyone know how to add colors to the plot? The code can be found below.

 def plot_donut(df):
 
    colors = ['#ca0020','#f4a582','#D9DDDC','#92c5de','#0571b0']
    
    trace1 = {
      "hole": 0.8, 
      "type": "pie", 
      "labels": ['-2','-1','0','1','2'], 
      "values": df['Time Spent (seconds)'], 
      "showlegend": False
 

    }

    fig = go.Figure(data=data, layout=layout)
    fig.show()
  
    
plot_donut(df)
like image 245
Jeroen Vermunt Avatar asked Jun 24 '26 20:06

Jeroen Vermunt


1 Answers

Further to my earlier comment, please see the code below for specifying named colours for a Plotly donut (pie) graph.

Like you, I much prefer to use the low-level Plotly API, rather than relying on the convenience wrappers. The code below shows how this is done at a low level.

Example code:

import plotly.io as pio

values = [2, 3, 5, 7, 11]
colours = ['#440154', '#3e4989', '#26828e', '#35b779', '#fde725']

trace1 = {'values': values, 
          'marker': {'colors': colours},  # <--- This is the key.
          'type': 'pie',
          'hole': 0.8,
          'showlegend': False}

pio.show({'data': [trace1]})

Output:

enter image description here

like image 62
S3DEV Avatar answered Jun 27 '26 09:06

S3DEV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!