更改标签后标记未显示在图例中(seaborn 和 matplotlib)

发布于 2025-01-19 07:39:05 字数 1059 浏览 3 评论 0原文

当我更改传奇标题时,我的两个标记中只有第一个是重新绘制的,我做错了什么,还是有解决方法?

我在下面运行了代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

#create dataframe
np.random.seed(seed=10)

x = np.arange(0,20)
y1 = np.arange(0,20) + 10*np.random.rand(20)
y2 = np.arange(20,0,-1) + 10*np.random.rand(20)
mask = np.random.randint(low=0, high=2, size=20, dtype=bool)

df = pd.DataFrame()

df['x'] = x
df['y1'] = y1
df['y2'] = y2
df['mask'] = mask

#plot results
fig, axs = plt.subplots(2)

f1 = sns.scatterplot(data=df, y='y1', x='x', ax=axs[0], hue="mask")
f2 = sns.scatterplot(data=df, y='y2', x='x', ax=axs[1], hue="mask")

new_title = ""
new_labels = ['Include', 'Exclude']

for ax in axs:
    ax.legend(title=new_title, labels=new_labels)
    
fig.savefig(r"C:\\Temp\error.png", bbox="tight")

结果在下面。如您所见,图例中的“ Include”标签具有标记,但“排除”标签不会

“在此处输入图像说明”

When I change the legend titles, only the first of my two markers is redrawn, am I doing something wrong, or is there a workaround?

I ran the code below:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

#create dataframe
np.random.seed(seed=10)

x = np.arange(0,20)
y1 = np.arange(0,20) + 10*np.random.rand(20)
y2 = np.arange(20,0,-1) + 10*np.random.rand(20)
mask = np.random.randint(low=0, high=2, size=20, dtype=bool)

df = pd.DataFrame()

df['x'] = x
df['y1'] = y1
df['y2'] = y2
df['mask'] = mask

#plot results
fig, axs = plt.subplots(2)

f1 = sns.scatterplot(data=df, y='y1', x='x', ax=axs[0], hue="mask")
f2 = sns.scatterplot(data=df, y='y2', x='x', ax=axs[1], hue="mask")

new_title = ""
new_labels = ['Include', 'Exclude']

for ax in axs:
    ax.legend(title=new_title, labels=new_labels)
    
fig.savefig(r"C:\\Temp\error.png", bbox="tight")

The result is below. As you can see the "Include" label in the legend has a marker, but the "Exclude" label does not

enter image description here

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文