我有一个sns.pairplot,轴外有图例。无论我如何调整bbox_to_anchor,除非我将图例的右侧放入轴中,否则图例的左侧会被切掉一点。
图例最初是这样定位的:

我可以通过以下方式成功调整图例的位置:
g._legend.set_bbox_to_anchor((1, .53, .0, 0))

无论我如何移动图例,总是图例的一小部分被截断。这真的很奇怪。这是不是因为某个调用:
plt.subplots_adjust(hspace=0.02, wspace=0.04)

下面是我调用来调整图例的所有命令:
g._legend.set_title('')
g._legend.set_bbox_to_anchor((1.01, .53, 0, 0))
#new_labels = ['Cluster 1', 'Cluster 2', 'Cluster 3'...]
new_labels = ['Cluster ' + str(i) for i in range(1, len(cluster_data[cluster_col_index].unique()+1))]
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)
for lh in g._legend.legendHandles:
lh.set_alpha(1)
lh._sizes = [70] 和
g._legend.borderpad=5也不工作..。
发布于 2020-09-11 14:48:23
您可以设置自己的图例。您可以使用plt.legend()设置图例。如果要删除原始图例,请启用ax._lengen.remove()。
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="ticks")
df = sns.load_dataset("penguins")
ax = sns.pairplot(df, hue="species")
# ax._legend.remove()
plt.legend(['Adelie', 'Chinstrap', 'Gentoo'], bbox_to_anchor=(0.9, 0.6))
plt.show()

发布于 2020-09-15 12:45:17
我只是想出了另一个解决方案。只需要添加更多的空间后,图例标签将工作。
想要更改代码:
new_labels = ['Cluster ' + str(i) for i in range(1, len(cluster_data[cluster_col_index].unique()+1))]
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)至:
new_labels = ['Cluster ' + str(i) + ' ' for i in range(1, len(cluster_data[cluster_col_index].unique()+1))]
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)https://stackoverflow.com/questions/63839082
复制相似问题