当我把它移到剧情之外时,传奇失去了第二位艺术家

时间:2018-05-22 21:45:43

标签: python-2.7 pandas matplotlib jupyter-notebook

当我向我的绘图添加第二个数据系列(带有辅助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

有一个简单的解决办法吗?

1 个答案:

答案 0 :(得分:0)

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

library(tidyverse)

DF %>% unite("col", starts_with("col"), sep=",") %>%
  mutate(col = strsplit(as.character(col), ",")) %>%
  unnest(col) %>% filter(col != "")

#    Company    col
# 1 Company1 test 1
# 2 Company2 test 2
# 3 Company4 test 3
# 4 Company4 test 4

要同时在同一个图例中,您可以从相应的图例手柄和标签

创建图例
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))

请注意,此图例可能仅适用于较新的matplotlib版本。另请注意,ax = tempDF.plot(y='y1') tempDF.plot(y='y2', ax=ax, secondary_y=True) ax.figure.legend(loc=(0.9,.9)) 的坐标现在是图形坐标,而不是轴坐标。