PathCollection'对象没有属性legend_elements''

时间:2019-11-26 18:57:19

标签: python-3.x matplotlib

我知道已经问过这个确切的问题here,但是当前的解决方案对我没有任何帮助。我似乎无法为每个标签生成具有不同颜色的图例。我已经尝试了Matplotlib上的当前文档,但无济于事。我不断收到我的PathCollection object has no attribute legend_elements

的错误消息

编辑:另外,我希望我的图例只是Years,对于该图而言,唯一的年份不是现在的样子,而是每个数据点都映射到我的图例。 这就是我所拥有的

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.pyplot import legend
import os

%config InlineBackend.figure_format = 'retina'

path = None
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        path = os.path.join(dirname, filename)

# Indexes to be removed
early_demo_dividend = 13
high_income = 24
lower_middle_income = 40
north_america = 46
members = 50
post_demo = 56
_removals = [early_demo_dividend, high_income, lower_middle_income, north_america, members, post_demo]

#Read in data
df = pd.read_csv(path)

#Get the rows we want
df = df.loc[df['1960'] > 1]
df = df.drop(columns=["Code", "Type", "Indicator Name"])

#Remove the odd rows
for i in _removals:
    df = df.drop(df.index[i])

#Format the dataframe
df = df.melt('Name', var_name='Year', value_name='Budget')

#Plot setup
plt.figure().set_size_inches(16,6)
plt.xticks(rotation=90)
plt.grid(True)

#Plot labels
plt.title('Military Spending of Countries')
plt.xlabel('Countries')
plt.ylabel('Budget in Billions')

#Plot data
new_year = df['Year'].astype(int)
scatter = plt.scatter(df['Name'], df['Budget'], c=(new_year / 10000) , label=new_year)

#Legend setup produce a legend with the unique colors from the scatter
legend1 = plt.legend(*scatter.legend_elements(),
                    loc="lower left", title="Years")
plt.add_artist(legend1)

plt.show()

这里是我的情节 enter image description here

2 个答案:

答案 0 :(得分:0)

我也遇到了这个问题。

尝试用matplotlib升级pip3 install --upgrade matplotlib

    Uninstalling matplotlib-3.0.3:
      Successfully uninstalled matplotlib-3.0.3
Successfully installed matplotlib-3.1.2

对我有用。

答案 1 :(得分:0)

尽管我的答案可能与当前问题无关,但我还是决定用它来描述我的情况-这可能对其他人有用:

如果在使用诸如scatterplot之类的matplotlib函数时,错误地指定了一些其他参数的名称,则会出现相同的错误。 示例:

x = list(range(10))
y = list(range(10))
plt.scatter(x, y, labels='RESULT')

我得到了错误:

AttributeError:“ PathCollection”对象没有属性“ labels”

如错误消息中所述(但对于不专心的开发人员而言,这并不明显:)): 我使用labels而不是label

的问题