0

我在这个情节中遇到了两个问题:

  1. 我试图在我的代码中添加其他功能,但是回归线在lmplot().
  2. 当我添加图例的设置时,左下角会添加另一个图例。但是,该设置确实将原始图例移到了我的情节之外。

这是我的代码:

g = sns.lmplot(x="fico", y="int.rate", col="not.fully.paid", data=loans, hue = 'credit.policy', palette = 'Set1', truncate = False, scatter_kws={"s": 10}, legend_out = True)

g.set(xlim = (550, 850))
g.set(ylim = (0, 0.25))

g.fig.tight_layout()
plt.legend(bbox_to_anchor=(1.3, 0), loc='upper right')

链接到我的情节:github链接

4

1 回答 1

0

lmplot()truncate=有一个默认为的选项,即将True回归线截断到第一个和最后一个点。 truncate=False将延长它们直到它们在绘图时达到 x 限制。您不想要默认的 xlim,并且lmplot()似乎没有提供预先设置这些限制的方法。一种方法可能是将默认的 x 边距设置得非常高(通过rcParams),然后将 x 限制缩回。

移动一个传奇是相当困难的。通常需要删除旧的并创建一个新的。在这种情况下,您可以legend=False在创建期间进行设置。然后再创建(有些图例比较复杂,需要很多手动参数)。

可以使用 来创建图例ax,在这种情况下ax是最后一个子图的 。该位置以“轴坐标”给出,从左下角的 0,0 到右上角的 1,1。稍微超出该范围的坐标将刚好在主绘图区域之外。当给定位置时,该loc=参数会告诉您涉及图例的哪个角。loc='upper left'传说的左上角也是如此。

这是一些示例代码:

import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl

sns.set_theme(style="ticks")
tips = sns.load_dataset('tips')
mpl.rcParams['axes.xmargin'] = 0.5  # set very wide margins: 50% of the actual range
g = sns.lmplot(x="total_bill", y="tip", col="smoker", hue="time", data=tips, truncate=False, legend=False)
mpl.rcParams['axes.xmargin'] = 0.05 # set the margins back to the default
# add the legend just outside the last subplot
g.fig.axes[-1].legend(bbox_to_anchor=(1.02, 1.01), loc='upper left', title='Time')
g.set(xlim = (0, 80)) # set the limits to the desired ones
plt.tight_layout() # fit labels and legend
plt.show()

lmplot

于 2021-03-23T16:45:27.983 回答