How to add caption & subtitle using plotly method in python

Maddy6 picture Maddy6 · Sep 30, 2019 · Viewed 7.3k times · Source

I'm trying to plot a bar chart using plotly and I wanted to add a caption and subtitle.(Here you can take any example of your choice to add caption and subtitle)
My code for plotting the bar chart:

import plotly.graph_objects as go  

fig = go.Figure()       

fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500])) 

fig.show()

Answer

vestland picture vestland · Sep 30, 2019

Use fig.update_layout(title_text='Your title') for your caption. There's no built-in option for subtitles. But you can get the desired effect by moving the x-axis labels to the top and at the same time insert an annotation at the bottom right. I've tried with other y-values as well, but there doesn't seem to be a way to get the annotations outside the plot itself. You could also change the fonts of the caption and subtitle to make them stand out from the rest of the labels.

Plot:

enter image description here

Code:

import plotly.graph_objects as go  

fig = go.Figure()       

fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500])) 


fig.update_layout(title=go.layout.Title(text="Caption", font=dict(
                family="Courier New, monospace",
                size=22,
                color="#0000FF"
            )))

fig.update_layout(annotations=[
       go.layout.Annotation(
            showarrow=False,
            text='Subtitle',
            xanchor='right',
            x=1,
            xshift=275,
            yanchor='top',
            y=0.05,
            font=dict(
                family="Courier New, monospace",
                size=22,
                color="#0000FF"
            )
        )])

fig['layout']['xaxis'].update(side='top')

fig.show()