【问题标题】:Single axis caption in plotly express facet plotplotly express 平面图中的单轴标题
【发布时间】:2020-01-29 16:44:11
【问题描述】:

我正在学习使用 pyplot.express 并努力解决以下设计问题:在多面图中,每个子图的轴标题都重复(在示例中为“花瓣宽度(厘米)”)。有没有办法使用 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()

【问题讨论】:

    标签: python graph plotly plotly-express


    【解决方案1】:

    这是执行此操作的 Plotly 原生方式

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

    【讨论】:

      【解决方案2】:

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

      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 轴添加了一个标题,并通过指定 yref="paper" 确保它始终位于绘图的中心

      剧情:

      【讨论】:

        【解决方案3】:

        感谢@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"
                )
            ]
        )
        

        【讨论】:

        • 这是一种非常优雅的方法。很高兴终于了解“论文”论点的作用......
        • 这对我有用,谢谢。我希望有一个更简单的方法来做到这一点,这对于这么简单的事情来说太过分了......奇怪的是情节没有选择它。
        猜你喜欢
        • 2020-05-14
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 1970-01-01
        • 2020-11-01
        • 2019-12-14
        • 2017-12-25
        • 2021-12-17
        相关资源
        最近更新 更多