【问题标题】:add legend seaborn barplot添加传奇 Seaborn 条形图
【发布时间】:2020-07-29 22:23:19
【问题描述】:

这是我的代码:

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()

不幸的是,我有这个错误:

TypeError: 'AxesSubplot' 对象不支持索引

我想知道为什么使用 seaborn 无法调用这样的图例 (plt.legend(ax[0]...) 而使用 matplotlib 则可以。 最后我只想要左上角的图例。

【问题讨论】:

    标签: python matplotlib seaborn legend


    【解决方案1】:

    我发现 barplot 有“标签”功能:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      相关资源
      最近更新 更多