作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我知道有人问过这个确切的问题 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()
最佳答案
我也遇到了这个问题。
尝试升级您的 matplotlib
与 pip3 install --upgrade matplotlib
Uninstalling matplotlib-3.0.3:
Successfully uninstalled matplotlib-3.0.3
Successfully installed matplotlib-3.1.2
关于python-3.x - PathCollection' 对象没有属性 legend_elements'',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59057691/
我刚刚将 matplotlib 升级到版本 3.1.1,并且正在尝试使用 legend_elements。 我正在 30,000 个扁平灰度图像的数据集上绘制 PCA 前两个分量的散点图。每张图像都标
我是一名优秀的程序员,十分优秀!