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

时间:2019-09-30 10:29:10

标签: python plotly

我正在尝试使用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()

3 个答案:

答案 0 :(得分:2)

Plotly 获取您的字符串并将其作为 HTML 传递。在标题字符串或 X 轴字符串中添加 HTML 可以让您在 ploty 图形对象和 plotly express 中添加一些快速副标题/标题。

<br> 是换行符,<sup> 是上标,可让您快速制作更小的副标题或标题。

图形对象:

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

图:

答案 1 :(得分:1)

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

情节:

enter image description here

代码:

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

答案 2 :(得分:0)

也许是这样吗?

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

Example