Plotly: How to set up a color palette for a figure created with multiple traces?

2024/11/16 8:41:06

I using code below to generate chart with multiple traces. However the only way that i know to apply different colours for each trace is using a randon function that ger a numerico RGB for color.

But random color are not good to presentations.

How can i use a pallet colour for code below and dont get more random colors?

groups53 = dfagingmedioporarea.groupby(by='Area')data53 = []
colors53=get_colors(50)for group53, dataframe53 in groups53:dataframe53 = dataframe53.sort_values(by=['Aging_days'], ascending=False)trace53 = go.Bar(x=dataframe53.Area.tolist(), y=dataframe53.Aging_days.tolist(),marker  = dict(color=colors53[len(data53)]),name=group53,text=dataframe53.Aging_days.tolist(),textposition='auto',)data53.append(trace53)layout53 =  go.Layout(xaxis={'title': 'Area', 'categoryorder': 'total descending', 'showgrid': False},yaxis={'title': 'Dias', 'showgrid': False},margin={'l': 40, 'b': 40, 't': 50, 'r': 50},hovermode='closest',template='plotly_white',title={'text': "Aging Médio (Dias)",'y':.9,'x':0.5,'xanchor': 'center','yanchor': 'top'})figure53 = go.Figure(data=data53, layout=layout53)
Answer

Many questions on the topic of plotly colors have already been asked and answered. See for example Plotly: How to define colors in a figure using plotly.graph_objects and plotly.express? But it seems that you would explicitly like to add traces without using a loop. Perhaps because the attributes for trace not only differ in color? And to my knowledge there is not yet a description on how to do that efficiently.


The answer:

  1. Find a number of available palettes under dir(px.colors.qualitative), or
  2. define your very own palette like ['black', 'grey', 'red', 'blue'], and
  3. retrieve one by one using next(palette) for each trace you decide to add to your figure.

And next(palette) may seem a bit cryptic at first, but it's easily set up using Pythons itertools like this:

import plotly.express as px
from itertools import cycle
palette = cycle(px.colors.qualitative.Plotly)
palette = cycle(px.colors.sequential.PuBu)

Now you can use next(palette) and return the next element of the color list each time you add a trace. The very best thing about this is, as the code above suggests, that the colors are returned cyclically, so you'll never reach the end of a list but start from the beginning when you've used all your colors once.

Example plot:

enter image description here

Complete code:

import plotly.graph_objects as go
import plotly.express as px
from itertools import cycle# colors
palette = cycle(px.colors.qualitative.Bold)
#palette = cycle(['black', 'grey', 'red', 'blue'])
palette = cycle(px.colors.sequential.PuBu# data
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")# plotly setup
fig = go.Figure()# add traces
country = 'Germany'
fig.add_traces(go.Bar(x=[country],y = df[df['country']==country]['pop'],name = country,marker_color=next(palette)))country = 'France'
fig.add_traces(go.Bar(x=[country],y = df[df['country']==country]['pop'],name = country,marker_color=next(palette)))country = 'United Kingdom'
fig.add_traces(go.Bar(x=[country],y = df[df['country']==country]['pop'],name = country,marker_color=next(palette)))fig.show()
https://en.xdnf.cn/q/71687.html

Related Q&A

Which implementation of OrderedDict should be used in python2.6?

As some of you may know in python2.7/3.2 well get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompati…

Signal Handling in Windows

In Windows I am trying to create a python process that waits for SIGINT signal.And when it receives SIGINT I want it to just print a message and wait for another occurrence of SIGINT.So I used signal h…

Python tkinter.filedialog askfolder interfering with clr

Im mainly working in Spyder, building scripts that required a pop-up folder or file Browse window.The code below works perfect in spyder. In Pycharm, the askopenfilename working well, while askdirector…

Run a function for each element in two lists in Pandas Dataframe Columns

df: col1 [aa, bb, cc, dd] [this, is, a, list, 2] [this, list, 3]col2 [[ee, ff, gg, hh], [qq, ww, ee, rr]] [[list, a, not, 1], [not, is, this, 2]] [[this, is, list, not], [a, not, list, 2]]What Im tryin…

cannot filter palette images error when doing a ImageEnhance.Sharpness()

I have a GIF image file. I opened it using PIL.Image and did a couple of size transforms on it. Then I tried to use ImageSharpness.Enhance() on it...sharpener = PIL.ImageEnhance.Sharpness(img) sharpene…

Is there a PyPi source download link that always points to the lastest version?

Say my latest version of a package is on PyPi and the source can be downloaded with this url:https://pypi.python.org/packages/source/p/pydy/pydy-0.3.1.tar.gzId really like to have a url that looks like…

Can this breadth-first search be made faster?

I have a data set which is a large unweighted cyclic graph The cycles occur in loops of about 5-6 paths. It consists of about 8000 nodes and each node has from 1-6 (usually about 4-5) connections. Im d…

How to remove rows of a DataFrame based off of data from another DataFrame?

Im new to pandas and Im trying to figure this scenario out: I have a sample DataFrame with two products. df = Product_Num Date Description Price 10 1-1-18 Fruit Snacks 2.9910 1-2-18 …

Amazon S3 Python S3Boto 403 Forbidden When Signature Has + sign

I am using Django and S3Boto and whenever a signature has a + sign in it, I get a 403 Forbidden. If there is no + sign in the signature, I get the resource just fine. What could be wrong here?UPDATE: …

List comparison of element

I have a question and it is a bit hard for me to explain so I will be using lots of examples to help you all understand and see if you could help me.Say I have two lists containing book names from best…