简体   繁体   English

添加图例 seaborn 条形图

[英]add legend seaborn barplot

Here is my code:这是我的代码:

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

array = np.array([[1,5,9],[3,5,7]])

df = pd.DataFrame(data=array, index=['Positive', 'Negative'])

f, ax = plt.subplots(figsize=(8, 6))

current_palette = sns.color_palette('colorblind')

ax_pos = sns.barplot(x = np.arange(0,3,1), y = df.loc['Positive'].to_numpy(), color = current_palette[2], alpha = 0.66)
ax_neg = sns.barplot(x = np.arange(0,3,1), y = df.loc['Negative'].to_numpy(), color = current_palette[4], alpha = 0.66)

plt.xticks(np.arange(0,3,1), fontsize = 20)
plt.yticks(np.arange(0,10,1), fontsize = 20)

plt.legend((ax_pos[0], ax_neg[0]), ('Positive', 'Negative'))

plt.tight_layout()

Unfortunately, I have this error:不幸的是,我有这个错误:

TypeError: 'AxesSubplot' object does not support indexing类型错误:'AxesSubplot' object 不支持索引

I would like to know why calling legend like this (plt.legend(ax[0]...) is not possible with seaborn whereas with matplotlib it is. In the end, I just want the legend in the upper left corner.我想知道为什么用 seaborn 不能调用这样的图例 (plt.legend(ax[0]...) 而用 matplotlib 是不可能的。最后,我只想要左上角的图例。

I figured out that barplot has "label" function:我发现 barplot 有“标签”function:

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

array = np.array([[1,5,9],[3,5,7]])

df = pd.DataFrame(data=array, index=['Positive', 'Negative'])

f, ax = plt.subplots(figsize=(8, 6))

current_palette = sns.color_palette('colorblind')

sns.barplot(x = np.arange(0,3,1), y = df.loc['Positive'].to_numpy(), color = current_palette[2], alpha = 0.66, label = "Positive")
sns.barplot(x = np.arange(0,3,1), y = df.loc['Negative'].to_numpy(), color = current_palette[4], alpha = 0.66, label = "Negative")

plt.xticks(np.arange(0,3,1), fontsize = 20)
plt.yticks(np.arange(0,10,1), fontsize = 20)

plt.legend(frameon = False)

plt.tight_layout()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM