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.

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

I see some examples using Text and Annotations but was wondering if there is any other approach to do it.
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/
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With