2 回答

TA貢獻1859條經驗 獲得超6個贊
當您scatterplot()使用hue=、 或style=等創建 a 時,seaborn 會自動在圖例列表中添加一個條目以充當“節標題”。
由于您正在重新創建圖例以將其放入所需的格式,因此要求 matplotlib 排除圖例列表中的第一個條目以擺脫該“標題”是非常簡單的
tips = sns.load_dataset('tips')
ax = sns.scatterplot(x="total_bill", y="tip", hue="day",
data=tips)
h,l = ax.get_legend_handles_labels()
plt.legend(h[1:],l[1:],ncol=3, loc='upper center',
bbox_to_anchor=[0.5, 1.25],
columnspacing=1.3, labelspacing=0.0,
handletextpad=0.0, handlelength=1.5,
fancybox=True, shadow=True)

TA貢獻1779條經驗 獲得超6個贊
您可以找到句柄和標簽 - 并從它們中刪除圖例標題。它們將是列表,其中包含您的圖例作為第一項。例如,labels您的示例如下所示:
labels = ['Pluton', 'Desemborque', 'Desemb. (hidrot. I)' ... and all others]
handles將包含類似的項目,但它們表示為matplotlib object:
handles = [<matplotlib.lines.Line2D object at 0x7f114408bf98>, ... and many others]
代碼:
import matplotlib.pyplot as plt
import seaborn as sns
# Set style for seaborn
sns.set_style("ticks")
x = sns.scatterplot(x="Al total", y="Fe/Fe+Mg", data=df, hue="Pluton", alpha=1)
# Found handles and labels for legend
ax = x.axes[0][0]
handles, labels = ax.get_legend_handles_labels()
# When set legend in matplotlib use our modified handles and labels
plt.legend(ncol=3, loc='upper center',
bbox_to_anchor=[0.5, 1.25],
columnspacing=1.3, labelspacing=0.0,
handletextpad=0.0, handlelength=1.5,
fancybox=True, shadow=True,
handles=handles[1:], labels=labels[1:],
)
# Plot
plt.ylim(0.2, 1.1)
plt.show()
可以建議也閱讀此以了解其他可能的方法
添加回答
舉報