我目前正在做一个Python项目,其中我正在使用此API构建一个饼形图,显示英格兰不同燃料类型的当前碳强度输出。我已经能够提取所需的数据,现在只需要使用matplotlib将其放入饼图中。这是我到目前为止拥有的代码。
import requests
import pprint
import matplotlib.pyplot as plt
import numpy as np
filename = ("https://api.carbonintensity.org.uk/regional/england")
r = requests.get(filename)
print("Status Code:", r.status_code)
#Store API responce in a variable
responce_dict = r.json()
# get data
datas = responce_dict["data"][0]["data"][0]["generationmix"]
# print data
pprint.pprint(datas)
for data in datas:
print(data["perc"])
for data in datas:
print(data["fuel"])
y = np.array([x for x in data["perc"]])
mylabels = ([x for x in data["fuel"]])
plt.pie("y", labels = mylabels)
plt.show()正如您所看到的,我正在使用列表理解来获取饼图所基于的每种燃料类型的碳强度的"perc“数据,以及获取每种燃料类型的标签的" fuel”数据。当我运行这段代码时,我得到了"TypeError:'float‘object is not iterable“的错误。我不确定我的代码出了什么问题,尽管我认为这可能是我的列表理解中的一个错误。谢谢。
发布于 2021-08-22 04:16:52
替换这些行
y = np.array([x for x in data["perc"]])
mylabels = ([x for x in data["fuel"]])
plt.pie("y", labels = mylabels)通过以下方式:
y = np.array([x['perc'] for x in datas])
mylabels = ([x['fuel'] for x in datas])
plt.pie(y, labels = mylabels)https://stackoverflow.com/questions/68878411
复制相似问题