I have a dataframe:
>>> import pandas as pd
>>> import plotly.express as px
>>> df = pd.DataFrame({
... 'P': ['P1', 'P2', 'P3'],
... 'Q1': [1, 2, 3],
... 'Q2': [3, 1, 2],
... })
>>> df
P Q1 Q2
0 P1 1 3
1 P2 2 1
2 P3 3 2
>>>
For each row, I should sort Qx columns in descending order, and than do plots but each Qx column should have the same color. Something like this:
qcols = [col for col in df.columns if col.startswith('Q')]
# I have to define colors in advance
color_dict = {col: color for col, color in zip(
qcols,
px.colors.qualitative.Plotly[:len(df)]
)}
for p in df.P.unique():
# Transformation needed for sorting columns descending
dfp = df.query("P == @p").set_index('P').T.sort_values(p, ascending=False).T.reset_index().melt(id_vars='P', var_name='Q', value_name='val')
fig = px.bar(data_frame=dfp, x='Q', y='val', color='Q', color_discrete_map=color_dict, width=300, height=300)
fig.show()
It looks quite complicated to me.
Can it be done in a simpler way?