首页 > 解决方案 > 为 plotly.graph_objs.Bar 类型的对象指定的属性无效

问题描述

我正在创建一个 api Web 调用来提取数据并使用 Plotly 将结果输出到条形图。我收到“为 plotly.graph_objs.Bar 类型的对象指定的无效属性”

#python_repos_visual.py
from plotly.graph_objs import Bar
from plotly import offline
import requests

#Make an api call and store the response
url = ('https://api.github.com/search'
'/repositories?q=language:python&sort=stars')
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f"Status code: {r.status_code}")

#Process results
response_dict = r.json()
repo_dicts = response_dict['items']
repo_names, stars = [], []
for repo_dict in repo_dicts:
    repo_names.append(repo_dict['name'])
    stars.append(repo_dict['stargazers_count'])

#Make visualization.
data = [{
    'type': 'bar',
    'x': repo_names,
    'y:': stars,
}]

my_layout = {
    'title': 'Most starred Python Projects on GitHub',
    'xaxis': {'title': 'Repository'},
    'yaxis': {'title': 'Stars'},
}
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='python_repos.html')

标签: pythonplotly

解决方案


我认为您应该更改导入并记住plotly仅从 4.0 版开始离线。

# Change your imports to
import plotly.graph_objs as go
import requests

# Make Visualization
trace = go.Bar(x=repo_names, y=stars)
my_layout = {
    'title': 'Most starred Python Projects on GitHub',
    'title_x': 0.5,
    'xaxis': {'title': 'Repository'},
    'yaxis': {'title': 'Stars'},
}

fig = go.Figure(data=trace, layout=my_layout)
fig.show()

推荐阅读