首页 > 解决方案 > python - 使用 loc 重新定位我的图例

问题描述

这是我的代码的输出

在此处输入图像描述

如您所见,图例“pl”和“ppl”在右上角重叠。我如何让其中一个移动到左上角。我尝试搜索 ans,并使用“loc”来解决问题,但不知何故我继续出错。有人可以帮忙吗?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.set_xlabel('Date')
ax1.set_ylabel('percent change / 100')
dd = pd.DataFrame(np.random.randint(1,10,(30,2)),columns=['pl','ppl'])
dd['pl'].plot(ax=ax1,legend=True)
dd['ppl'].plot(ax=ax2, style=['g--', 'b--', 'r--'],legend=True)

ax2.set_ylabel('difference')
plt.show()

标签: pythonpandasmatplotliblegend

解决方案


也许直接用 matplotlib 绘图而不是使用DataFrame.plot

ax1.plot(dd['pl'], label='pl')
ax1.legend(loc='upper left')
ax2.plot(dd['ppl'], ls='--', c='g', label='ppl')
ax2.legend(loc='upper right')

输出:

在此处输入图像描述


推荐阅读