一种方法是将
xref
设置为轴 ID,而不是“paper”,这样标题就可以相对于相应的 x 轴坐标左对齐。
然而,正如 @Derek O 所提到的,棘手的部分在于如何在迭代过程中识别注释。考虑到输入数据已经被索引(
for i in range(10)
中的
i
是正确的),您可以使用此索引来检索相应的 xref,唯一的要求是保持(或创建)它们之间的映射。为了说明这一点,在子图标题中直接放置了索引:
K = 10
R = 5
items = np.repeat([f'{i}={lorem.sentence()}' for i in range(K)], R)
response = list(range(1,6)) * K
n = [random.randint(0, 10) for i in range(K*R)]
facet_col_wrap = 4
nrows = math.ceil(K / facet_col_wrap)
ncols = min(K, facet_col_wrap)
fig = px.bar(x=response, y=n, facet_col=items, facet_col_wrap=facet_col_wrap, height=1300)
xrefs = []
for r in range(nrows)[::-1]:
for c in range(ncols):
subplot_ref = fig._grid_ref[r][c][0]
xrefs.append(subplot_ref.trace_kwargs['xaxis'])
def updateAnnotation(a):
_, i, title = a.text.split("=")
a.update(text=title, xanchor='left', x=0, xref=xrefs[int(i)])
(
fig
.for_each_annotation(updateAnnotation)
.for_each_xaxis(lambda xaxis: xaxis.update(showticklabels=True))
.for_each_yaxis(lambda xaxis: xaxis.update(showticklabels=True))
.show()
)
检查fig._grid_ref
中的SubplotRef
非常有帮助,一个SubplotRef
看起来像:
SubplotRef(subplot_type='xy', layout_keys=('xaxis', 'yaxis'), trace_kwargs={'xaxis': 'x', 'yaxis': 'y'})
更好的是:
>>> fig.print_grid()
This is the format of your plot grid:
[ (3,1) x9,y9 ] [ (3,2) x10,y10 ] [ (3,3) x11,y11 ] [ (3,4) x12,y12 ]
[ (2,1) x5,y5 ] [ (2,2) x6,y6 ] [ (2,3) x7,y7 ] [ (2,4) x8,y8 ]
[ (1,1) x,y ] [ (1,2) x2,y2 ] [ (1,3) x3,y3 ] [ (1,4) x4,y4 ]
facet_col_wrap
传递到你分配给fig
的部分中,然后稍后从fig
中提取出来,并在需要它的地方进行传递(例如在remainder
中)。我之所以这样问是因为将您的代码封装为一个方法并能够从传递给它的 fig 对象中了解facet_col_wrap
将会很好。 - Tyler Rinkerfig.layout['xaxis'],fig.layout['xaxis2']...
以及找出唯一区间的数量 - 我会相应地更新我的答案。 - Derek Ofig.layout
中每个原始注释中唯一x值的数量-答案已经更新,让我知道这看起来是否不错! - Derek Opx.scatter
图形上需要进行一次小的更新:使用len(fig.data)
计算remainder
和number_full_rows
是不正确的,这导致最后一行的子图标题重叠在一起。这些代码需要更新为remainder = len(fig.layout.annotations) % facet_col_wrap
和number_of_full_rows = len(fig.layout.annotations) // facet_col_wrap
。希望这能帮助某人避免一点小麻烦。 - undefined