【问题标题】:Annotations varying by subplot with plotly-express?注释因子图而异,情节表达?
【发布时间】:2020-07-28 04:27:53
【问题描述】:

假设我想制作一个像这样的子图,其中每个方面都有自己的 y 比例:

import plotly.express as px

fig = px.scatter(px.data.iris(), x='sepal_length', y='sepal_width', facet_col='species')


def update(y):
    y.update(matches=None)
    y.showticklabels=True

fig.for_each_yaxis(update)

现在假设我想添加一些注释,并且位置会根据 faceted 变量而变化,我在数据框中有这个:

如果我使用 plotnine/ggplot 我可以这样做:

ggplot(df_iris, aes(x='sepal_length', y='sepal_width')) + geom_point() + facet_wrap("~species", scales="free_y") + geom_text(aes(x='x', y='y', label='label'), data=df_text) 

是否有可能在情节中做到这一点?我对子图和注释陷入了困境,我知道您可以向子图添加注释,但是您必须知道行号和列号才能做到这一点,而且我不确定如何映射刻面变量(物种)到子图行/列索引。

谢谢:)

【问题讨论】:

    标签: plotly ggplotly plotly-python


    【解决方案1】:

    我不确定这是否是最好的方法,但您可以尝试以下方法

    import plotly.express as px
    import pandas as pd
    
    df_text = pd.DataFrame({"species":["setosa", "versicolor", "virginica"],
                            "x": [7, 7, 5],
                            "y": [3, 2, 3.5],
                            "label":["label1", "label2", "label3"]})
    
    fig = px.scatter(px.data.iris(),
                     x='sepal_length',
                     y='sepal_width',
                     facet_col='species')
    
    # Here are your annotations
    data = px.scatter(df_text,
                      x="x",
                      y="y",
                      text="label",
                      facet_col='species')\
              .update_traces(mode="text")["data"]
    
    def update(y):
        y.update(matches=None)
        y.showticklabels=True
        
    fig.for_each_yaxis(update)
    
    for trace in data:
        fig.add_trace(trace)
    
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多