如何编辑海洋传奇标题和图形功能的标签

发布于 2025-02-09 22:24:45 字数 515 浏览 3 评论 0原文

我已经使用seaborn和pandas dataframe(data)创建了此图:

“在此处输入图像说明”

我的代码:

import seaborn as sns

g = sns.lmplot('credibility', 'percentWatched', data=data, hue='millennial', markers=["+", "."])

您可能会注意到该情节的传奇标题只是变量名('千年')传说项目是其值(0,1)。如何编辑传奇的标题和标签?理想情况下,传奇标题将是“世代”,标签将是“千禧一代”和“老一辈”。

I've created this plot using Seaborn and a pandas dataframe (data):

enter image description here

My code:

import seaborn as sns

g = sns.lmplot('credibility', 'percentWatched', data=data, hue='millennial', markers=["+", "."])

You may notice the plot's legend title is simply the variable name ('millennial') and the legend items are its values (0, 1). How can I edit the legend's title and labels? Ideally, the legend title would be 'Generation' and the labels would be "Millennial" and "Older Generations".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

征﹌骨岁月お 2025-02-16 22:24:45

花了我一段时间来通读以上。这是我的答案:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=False
)

plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)

参考更多参数:

Took me a while to read through the above. This was the answer for me:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=False
)

plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)

Reference this for more arguments: matplotlib.pyplot.legend

enter image description here

抚你发端 2025-02-16 22:24:45
  • 如果legend_out将设置为true,则可以通过g._legend属性获得Legend,它是图的一部分。 Seaborn Legend是标准Matplotlib传奇对象。因此,您可以更改传奇文本。
  • python 3.8.11中测试,matplotlib 3.4.3seaborn 0.11.2
import seaborn as sns

# load the tips dataset
tips = sns.load_dataset("tips")

# plot
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels):
    t.set_text(l)

如果legend_out设置为false,则另一种情况。您必须定义哪个轴具有传奇(在示例中为轴号0):

g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': False})

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels):
    t.set_text(l)

”在此处输入图像说明”

您可以将两种情况结合起来并使用此代码:

g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels):
    t.set_text(l)

​基于

  • If legend_out is set to True then legend is available through the g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts.
  • Tested in python 3.8.11, matplotlib 3.4.3, seaborn 0.11.2
import seaborn as sns

# load the tips dataset
tips = sns.load_dataset("tips")

# plot
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels):
    t.set_text(l)

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': False})

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels):
    t.set_text(l)

enter image description here

Moreover you may combine both situations and use this code:

g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels):
    t.set_text(l)

enter image description here

This code works for any seaborn plot which is based on Grid class.

白馒头 2025-02-16 22:24:45

为了自定义传说,您需要直接操纵传说对象。 Seaborn中的传说存储在情节对象中。通过此传奇对象,您可以选择标题并修复标签的详细信息,以了解您的数据类型。

您可以做到这一点:

g = sns.lmplot('credibility', 'percentWatched', data=data, hue='millennial', markers=["+", "."])

g.set(title='Generation', xlabel='Credibility', ylabel='Percent Watched')
g._legend.set(title='Generation', labels=["Millennial", "Older Generations"])

plt.show()

For the customization of the legend, you need to manipulate the legend object directly. The legend in Seaborn is stored within the plot object. Through this legend object, you can select the title and fix the label's details for your type of data.

Here's how you can do this:

g = sns.lmplot('credibility', 'percentWatched', data=data, hue='millennial', markers=["+", "."])

g.set(title='Generation', xlabel='Credibility', ylabel='Percent Watched')
g._legend.set(title='Generation', labels=["Millennial", "Older Generations"])

plt.show()
瑾兮 2025-02-16 22:24:45

以下是编辑海洋人物传说的其他一些方法(从Seaborn 0.13.2开始)。

  1. 由于此处的传奇来自列传递给hue,这是最简单的方法(以及一种需要最少的工作IMO),如上所述在注释中将其用作hue变量。

     进口Seaborn作为SNS
    df = sns.load_dataset(“提示”)
    
    g = sns.lmplot(
        x ='total_bill',y ='tip', 
        data = df.Assign(性别= df ['sex']。地图({'男性':'男人','女性':'woman'})),#添加一个新列
        色相='性别',#< ---使用新列作为色调
        标记= [“+”,“。”]
    )
     
  2. 另一种方法是隐藏默认的传说,并使用add_legend()

      g = sns.lmplot(x ='total_bill',y ='tip',data = df,hue ='sex ='sex',markers = [“+” ,“。”]))
    g.legend.set_visible(false)#隐藏原始传说(也可以将`legend = false“ false”传递给上面的绘图调用)
    
    #使用旧数据创建新的传奇数据
    映射= {'男性':'男人','女性':'女人'}
    leg_data = {映射[k]:v for K,v in G._legend_data.items()}}
    #将新的传奇数据添加到图
    g.add_legend(legend_data = leg_data,title ='性别',label_order = list(leg_data))
     
  3. @serenity的答案效果很好,但是它不检查标签是否由正确的新标签替换。您可以使用IF-ELSE块进行操作,并确保用正确的标签替换标签。另外,您可以使用Legend而不是_legend

      g = sns.lmplot(x ='total_bill',y ='tip',data = df,hue ='sex ='sex',markers = [“+” ,“。”]))
    g.legend.set_title(“性别”)
    对于g.legend.texts中的标签:
        如果label.get_text()==“男性”:
            label.set_text(“男人”)
        别的:
            label.set_text(“女人”)
     

上述所有选项都执行了编辑图例的以下转换。

Here are some other ways to edit the legend of a seaborn figure (as of seaborn 0.13.2).

  1. Since the legend here comes from the column passed to hue, the easiest method (and one that requires the least work imo), as mentioned in comments, is to add a column to the dataframe and use it as the hue variable.

    import seaborn as sns
    df = sns.load_dataset("tips")
    
    g = sns.lmplot(
        x='total_bill', y='tip', 
        data=df.assign(Gender=df['sex'].map({'Male': 'man', 'Female': 'woman'})),   # add a new column
        hue='Gender',               # <--- use the new column as hue
        markers=["+", "."]
    )
    
  2. Yet another method is to hide the default legend and add a legend with the new labels and title using add_legend().

    g = sns.lmplot(x='total_bill', y='tip', data=df, hue='sex', markers=["+", "."])
    g.legend.set_visible(False)   # hide the original legend (can also pass `legend=False` to the plot call above)
    
    # create new legend data using the old data
    mapping = {'Male': 'man', 'Female': 'woman'}
    leg_data = {mapping[k]: v for k,v in g._legend_data.items()}
    # add the new legend data to the figure
    g.add_legend(legend_data=leg_data, title='Gender', label_order=list(leg_data))
    
  3. @Serenity's answer works well but it doesn't check if a label is replaced by the correct new label. You can do so using an if-else block and make sure to replace a label with the correct label. Also, you can use legend instead of _legend.

    g = sns.lmplot(x='total_bill', y='tip', data=df, hue='sex', markers=["+", "."])
    g.legend.set_title("Gender")
    for label in g.legend.texts:
        if label.get_text() == "Male":
            label.set_text("man")
        else:
            label.set_text("woman")
    

All of the above options perform the following transformation where the legend is edited.

result

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文