【问题标题】:Legend loses second artist when I move it outside plot当我将传奇移出情节时,传奇失去了第二位艺术家
【发布时间】:2018-11-01 18:21:46
【问题描述】:

当我在绘图中添加第二个数据系列(带有辅助 y 轴)并尝试移动图例时,我失去了对第二个系列的引用。如果我不尝试移动图例位置,它会起作用,但最佳情况下我想将图例放在情节之外。有没有快速解决方法?

这在图例中有两个系列标签:

import pandas as pd
import numpy as np

x = np.arange(0,100,1)
y1 = x
y2 = x**2

tempDF = pd.DataFrame({'y1': y1, 'y2': y2}, index=x)

ax = tempDF.plot(y='y1')
tempDF.plot(y='y2', ax=ax, secondary_y=True)

Default behavior

当我添加以下代码来移动图例时,我丢失了第二个系列标签:

ax.legend(loc=(1.15,.9))

Legend loses second series

有简单的解决方法吗?

【问题讨论】:

    标签: python-2.7 pandas matplotlib jupyter-notebook


    【解决方案1】:

    首先,你当然可以为每个轴添加一个图例,

    ax = tempDF.plot(y='y1')
    ax2 = tempDF.plot(y='y2', ax=ax, secondary_y=True)
    
    ax.legend(loc=(0.9,.9))
    ax2.legend(loc=(0.9,.8))
    

    要将两者放在同一个图例中,您可以从各自的图例句柄和标签创建图例,

    ax = tempDF.plot(y='y1')
    ax2 = tempDF.plot(y='y2', ax=ax, secondary_y=True)
    
    h1, l1 = ax.get_legend_handles_labels()
    h2, l2 = ax2.get_legend_handles_labels()
    ax.legend(h1+h2, l1+l2, loc=(0.9,.9))
    

    另一种方法是使用图形图例。

    ax = tempDF.plot(y='y1')
    tempDF.plot(y='y2', ax=ax, secondary_y=True)
    
    ax.figure.legend(loc=(0.9,.9))
    

    请注意,此图例可能仅适用于较新的 matplotlib 版本。另请注意,loc 的坐标现在是图形坐标而不是轴坐标。

    【讨论】:

    • 这行得通 - 谢谢!我尝试了图例,但我目前已降级为一个非常旧版本的 matplotlib。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多