I would like to use Python to draw a mosaic | marimekko chart with custom colors and labels.
The following code works fine
import plotly.graph_objects as go
year = ['2019', '2020', '2021', '2022']
fig1 = go. Figure()
fig1.add_trace(go.Bar(x=year, y=[20, 18, 14, 10], text=['20', '18', '14', '10'], name='brand 1'))
fig1.add_trace(go.Bar(x=year, y=[10, 15, 20, 22], text=['10', '15', '20', '22'], name='brand 2'))
fig1.add_trace(go.Bar(x=year, y=[6, 8, 10, 12], text=[ '6', '8', '10', '12'], name='brand 3'))
fig1.update_layout(barmode='stack')
fig1.write_image('test_1.png')
However, I want to sort the data for each year by the data passed via y. That means the code would look like (I'll leave out the sorting, that's not the question here).
fig2.add_trace(go.Bar(x=year, y=[20, 18, 20, 22], text=['20: brand 1', '18: brand 1', '20: brand 2', '22: brand 2']))
fig2.add_trace(go.Bar(x=year, y=[10, 15, 14, 12], text=['10: brand 2', '15: brand 2', '14: brand 1', '12: brand 3']))
fig2.add_trace(go.Bar(x=year, y=[ 6, 8, 10, 10], text=[ '6: brand 3', '8: brand 3', '10: brand 3', '10: brand 1']))
Of course, I still want to use the same colors per brand (not per position), so in addition to the appropriately sorted data, I need to pass two more arrays for custom label texts (works fine) and for the corresponding custom colors (I don't see how to do that).
Question 1: How can I pass an array of custom colors to each trace so that each brand always gets the same color? Is there anyling like
fig1.add_trace(go.Bar(x=year, y=[20, 18, 14, 10], colors=...))
Question 2: Is there another option to create a mosaic | marimekko chart with varying x-widths which is not based on plotly?
The expected code is something like
# the color map
the_brand_cmap = plt.get_cmap('seismic_r')
the_brand_norm = co.TwoSlopeNorm(vmin=-max_abs, vcenter=0, vmax=max_abs)
...
for i in years: # the loop is over the years, not over the brands!
# some more code to sort df per year and to extract the brand names and colors per year
fig1.add_trace(go.Bar( # this adds a trace for the i-th year
x=np.cumsum(xwidths) - xwidths,
y=ysizes_norm,
width=xwidths,
marker_color=the_brand_cmap(the_brand_norm(colors)), # the colors for each year
text=brand_name)
The expected result is