plotly express facet plot 中的单轴标题

Single axis caption in plotly express facet plot

我正在学习使用 pyplot.express 并努力解决以下设计问题:在多面图中,每个子图都会重复轴标题(在示例中 'petal width (cm)')。有没有办法使用 pyplot.express?

为多面图上的所有子图获取单轴标签

谢谢,迈克尔

最小示例:

from sklearn.datasets import load_iris
import plotly.express as px
import pandas as pd
import numpy as np

# import iris-data
iris = load_iris()
df= pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target'])
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

# plot using pyplot.express
fig = px.bar(df, x="sepal length (cm)", y="petal width (cm)", color = 'petal length (cm)', facet_row="species")
fig.show()

对于这种特殊情况,在您的示例片段之后,只需 运行

fig['layout']['yaxis']['title']['text']=''
fig['layout']['yaxis3']['title']['text']=''
fig.show()

或者,对于多个子图的更通用方法,只需 运行:

fig.for_each_yaxis(lambda y: y.update(title = ''))
# and:
fig.add_annotation(x=-0.1,y=0.5,
                   text="Custom y-axis title", textangle=-90,
                    xref="paper", yref="paper")

我还使用 fig.add_annotation() 为所有 y-axes 添加了标题,并通过指定 yref="paper"

确保它始终位于绘图的中心

剧情:

感谢@vestland 帮了大忙!

我根据你的回答想出了一个更灵活的设计方法(多个facet_rows):

首先我需要删除所有子图轴:

for axis in fig.layout:
    if type(fig.layout[axis]) == go.layout.YAxis:
        fig.layout[axis].title.text = ''

下一步是添加注释而不是轴,因为布局中的 yaxis 属性总是会修改其中一个轴的比例并弄乱绘图。搜索注释,我找到了 link 如何添加自定义轴。 xref='paper'yref='paper' 需要独立于子图定位标签。

fig.update_layout(
    # keep the original annotations and add a list of new annotations:
    annotations = list(fig.layout.annotations) + 
    [go.layout.Annotation(
            x=-0.07,
            y=0.5,
            font=dict(
                size=14
            ),
            showarrow=False,
            text="Custom y-axis title",
            textangle=-90,
            xref="paper",
            yref="paper"
        )
    ]
)

这是执行此操作的 Plotly 本机方法

    fig.update_yaxes(title='')
    fig.update_layout(yaxis2=dict(title="Custom Title"))