如何重命名 seaborn 散点图图例中的标签和标题?

How to rename labels and title in seaborn scatterplot legend?

我想更改以下图例:

我想将标题从 State 更改为 Place,将 Transition 更改为 Kilometers,并且 State 下面的标签需要从0City1Rural2Other。我还想将 Transition 值更改为整数而不是浮点数。此外,我希望新标题以粗体显示并朝向左侧而不是值的正上方。

我不确定这一切是否可行以及如何最好地解决这个问题...

我通过 运行 以下代码获得了这个图例(请记住,该图是 ax2 的一部分):

sns.scatterplot(data = data, x = 'x', y = 'y', size = 'Transition', hue = 'State', palette = 'flare', ax = ax2, legend = 'full')
ax2.legend(bbox_to_anchor = (1.05, 1), loc = 2, borderaxespad = 0)

最简单的方法是将 data 更改为所需的值:map the places and convert the kilometers with astype

如果您希望保持 data 完整,assign 情节调用中的变化:

places = {0: 'City', 1: 'Rural', 2: 'Other'}

sns.scatterplot(data=data.assign(Place=data['State'].map(places), Kilometers=data['Transition'].astype(int)),
                x='x', y='y', size='Kilometers', hue='Place', palette='flare', ax=ax2, legend='full')

或者您可以预先进行更改in-place:

data = data.rename(columns={'State': 'Place', 'Transition': 'Kilometers'})
data['Place'] = data['Place'].map({0: 'City', 1: 'Rural', 2: 'Other'})
data['Kilometers'] = data['Kilometers'].astype(int)

sns.scatterplot(data=data, x='x', y='y', size='Kilometers', hue='Place', palette='flare', ax=ax2, legend='full')

What about making the legend titles (Place and Kilometers) bold and slightly larger, and also maybe leftward shifted?

似乎 seaborn 手动重建图例,所以这些标题不是真的 title objects。我不确定是否有更好的方法,但您可以用这样的方法替换当前的 ax2.legend(...) 调用:

# first remove the line: ax2.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)

# then get the existing seaborn legend and alter it
leg2 = ax2.get_legend()
leg2.set_bbox_to_anchor((1.05, 1))
for t in leg2.get_texts():
    if t.get_text() in ['Place', 'Kilometers']:
        t.set_weight('bold')
        t.set_fontsize('large')