如何在Plotly中创建子图后更改子图标题?

9

使用 Matplotlib 我可以做到这一点:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 2, figsize=(10, 5))
fig.patch.set_facecolor('white')

axs[0].bar(x=[0,1,2], height=[1,2,3])
axs[1].plot(np.random.randint(1, 10, 50))

axs[0].set_title('BARPLOT')
axs[1].set_title('WOLOLO')

enter image description here

使用Plotly,我只知道一种方法来设置子图标题——在创建时:fig = make_subplots(rows=1, cols=2, subplot_titles=('title1', 'title2'))

是否可以在创建后设置子图标题?
也许可以通过获取基于Matplotlib的原始Axes类(我读到plotly.python基于Seaborn,Seaborn基于Matplotlib)来实现?
或者通过fig.layout实现?

请使用以下代码:

import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2)
fig.add_trace(go.Bar(y=[1, 2, 3]), row=1, col=1)
fig.add_trace(go.Scatter(y=np.random.randint(1, 10, 50)), row=1, col=2)

enter image description here

1个回答

13
以下代码可实现您想要的功能。
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2, subplot_titles=("Plot 1", "Plot 2"))
fig.add_trace(go.Bar(y=[1, 2, 3]), row=1, col=1)
fig.add_trace(go.Scatter(y=np.random.randint(1, 10, 50)), row=1, col=2)

fig.layout.annotations[1].update(text="Stackoverflow")

fig.show()

我从 https://community.plotly.com/t/subplot-title-alignment/33210/2 得到了这个想法,其中描述了如何访问每个图的注释。


1
所以,基本上我们需要指定初始字幕作为占位符,然后我们就能够迭代并更改它们。谢谢! - banderlog013

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接