matplotlib图例在手动设置坐标时避免使用点

时间:2017-12-08 16:04:07

标签: python matplotlib

在下面的代码中,我生成一个散点图,手动放置图例:

#!/usr/bin/env python3

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

frame = frame = pd.DataFrame({"x": [1, 2, 3, 4], "y": [4, 3, 2, 1]})
ax = frame.plot.scatter(x="x", y="y", label="dots")
plt.savefig("dots.pdf")
for y in [0.6, 0.7, 0.8]:
    ax.legend(bbox_to_anchor=(0.5, y), bbox_transform=ax.transAxes)
    plt.savefig("dots_{}.png".format(y))

如果图例隐藏了一个点,它似乎不遵守放置说明:

y=0.6 y=0.7 y=0.8

有没有办法避免这种情况?我的意思是,如何真正强制放置传奇?

1 个答案:

答案 0 :(得分:1)

您可能有兴趣阅读my answer to "How to put the legend out of the plot"。虽然它处理将图例放在图表之外的情况,但大多数情况适用于将图例放置在任何位置,包括图中。

最重要的是,图例位置由loc参数决定。如果您未在legend()的调用中指定此参数,则matplotlib将尝试放置其认为最佳的图例(默认为loc ="best")。

如果您想将图例放在某个位置,可以将左下角的坐标指定为loc

ax.legend(loc=(0.5, 0.6))

如果要将图例的另一个角指定为某个位置,则需要使用loc参数指定一个角,并使用bbox_to_anchor指定位置:

ax.legend(loc="upper right", bbox_to_anchor=(0.5, 0.6))
相关问题