如何在 python 中使用 plotly 方法添加标题和副标题

How to add caption & subtitle using plotly method in python

我正在尝试使用 plotly 绘制条形图,我想添加标题和副标题。(在这里您可以选择任何示例来添加标题和副标题)
我绘制条形图的代码:

import plotly.graph_objects as go  

fig = go.Figure()       

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

fig.show()

也许是这样的?

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="Plot Title",
        xref="paper",
        x=0
    ),
    xaxis=go.layout.XAxis(
        title=go.layout.xaxis.Title(
            text="x Axis",
            font=dict(
                family="Courier New, monospace",
                size=18,
                color="#7f7f7f"
            )
        )
    ),
    yaxis=go.layout.YAxis(
        title=go.layout.yaxis.Title(
            text="y Axis",
            font=dict(
                family="Courier New, monospace",
                size=18,
                color="#7f7f7f"
            )
        )
    )
)
fig.show()

使用 fig.update_layout(title_text='Your title') 作为标题。没有 built-in 字幕选项。但是您可以通过将 x-axis 标签移动到顶部并同时在右下角插入注释来获得所需的效果。我也尝试过其他 y-values,但似乎没有办法在情节本身之外获取注释。您还可以更改标题和副标题的字体,使其从其余标签中脱颖而出。

剧情:

代码:

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()

Plotly 获取您的字符串并将其作为 HTML 传递。在标题字符串或 X 轴字符串中添加 HTML 可以让您在 plotly graph objects 和 plotly express 中快速输入一些 subtitles/captions。

<br> 是换行符,<sup> 是上标,可以让您快速制作更小的字幕。

图表objects:

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="Plot Title <br><sup>Plot Subtitle</sup>",
        xref="paper",
        x=0
    ),
        xaxis=go.layout.XAxis(
        title=go.layout.xaxis.Title(
            text="Fruits<br><sup>Fruit sales in the month of January</sup>"
            )
        )
    )

fig.show()

情节表达:

import plotly.express as px
fig = px.bar(
    x=["Apple", 'Mango', 'Banana'], 
    y=[400, 300, 500],
    title = "Plot Title <br><sup>Plot Subtitle</sup>",
    labels = {'x':"Fruits<br><sup>Fruit sales in the month of January</sup>", 
              'y':'count'}
)
fig.show()

图: