Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: How to add a text box under legend?

I use this example code given in plotly website.

import plotly.express as px
df = px.data.medals_long()

fig = px.bar(df, x="medal", y="count", color="nation",
             pattern_shape="nation", pattern_shape_sequence=[".", "x", "+"])
fig.show()

This gives a plot like below. enter image description here

How can I add a text box under the legend in the plot to get it like in the picture below? enter image description here

I see some examples using Text and Annotations but was wondering if there is any other approach to do it.

like image 847
aj7amigo Avatar asked Oct 23 '25 18:10

aj7amigo


2 Answers

From what I could find, adding an annotation is the only way to get the expected output natively in plotly.

An implemntation of the annotation will look like:

fig.add_annotation(text='South Korea: Asia <br>China: Asia <br>Canada: North America', 
                    align='left',
                    showarrow=False,
                    xref='paper',
                    yref='paper',
                    x=1.1,
                    y=0.8,
                    bordercolor='black',
                    borderwidth=1)

Some additional html attributes you can add to the text attribute be found here: https://plotly.com/chart-studio-help/adding-HTML-and-links-to-charts/

like image 169
veedata Avatar answered Oct 25 '25 06:10

veedata


In addition to the accepted answer.

For me setting x=1.1 didn't directly put the text box on the same vertical line under the legend.

text not on the same line with legend

My legend settings:

{
  orientation="v",
  y=1,
  x=1,
}

However, setting xanchor="left" and x=1 for annotation made both legend and text appear on the same vertical line. So my total annotations config is:

fig.add_annotation(
    text="Some<br>multi-line<br>text",
    align="left",
    showarrow=False,
    xref="paper",
    yref="paper",
    font=dict(color="white", size=9),
    bgcolor="rgba(0,0,0,0)",
    y=0.2,
    x=1,
    xanchor="left",
)

Suppose this is because default xanchor value for legend if left (docs) while for annotations it is auto (docs)

like image 37
Artem Yankin Avatar answered Oct 25 '25 07:10

Artem Yankin



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!