python - 初始化 Plotly 的 Scattergeo fig 的不同方法,一种不允许我“update_geos”,另一种我不能添加数据
问题描述
我是使用 Plotly 的新手,但在学习了一些教程后,我决定开始自己的项目来研究公司的碳足迹。我配置了我自己的 JSON 数据并使用我想要的数据创建了一个 Scattergeo 图。当我想将边界从大陆更改为国家并将其更改为正交视图时,问题就出现了。从 Plotly 网站上,我找到了可以做到这一点的行:fig.update_geos(projection_type="orthographic, showcountries=True")
当我添加该代码时出现了我的问题,然后我得到了错误:AttributeError: 'dict' object has no attribute 'update_geos'
然后我意识到我这样做的方式和它在 Plotly 网站上的显示方式是不同的。我通过首先像这样导入来创建我的可视化:from plotly.graph_objs import Scattergeo, Layout
和from plotly import offline
. Plotly 所做的只是这行:import plotly.graph_objects as go
.
我通过在字典中编写这样的代码来定义我的数据:data = [{}]
并将我的布局定义为my_layout = Layout(title='How you measure up: Companies')
然后创建 fig fig = {'data': data, 'layout': my_layout}
。
在网站上,代码被简单地编写为fig = go.Figure(go.Scattergeo())
初始化可视化和所有内容。
显然,我学到了一种不同于 Plotly 使用的方法。我尝试以几种不同的方式混合我的代码来结合 Plotly 的代码和我的代码。我希望你们可以帮助我更改我自己的代码以允许该fig.update_geos
语句,或者为我指出一个教程或解决方案,在那里我可以学习如何将我自己的数据添加到 Plotly 的解决方案中。
我在下面附上了我的和 Plotly 的代码,以防有人想看看,我希望这个问题描述了我的问题,但我认为它可能会有所帮助,即使它有点长。
我的代码;我不知道如何在视觉上更新它或将其更改为正交视图。
import json
from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
filename = 'compPrint1.json'
with open(filename) as f:
all_json_data = json.load(f)
readable_file = 'readable_json_data.json'
with open(readable_file, 'w') as f:
json.dump(all_json_data, f, indent=4)
# cfp = Carbon FootPrint
companies, cfp, locations, lats, longs = [], [], [], [], []
for json_data in all_json_data:
company = json_data['company']
cp = json_data['carbonprint']
location = json_data['location']
lat = json_data['Latitude']
long = json_data['Longitude']
companies.append(company)
cfp.append(cp)
locations.append(location)
lats.append(lat)
longs.append(long)
companycfp = []
for json_data in all_json_data:
comp = json_data['company']
fp = json_data['carbonprint']
stringfp = str(fp)
compfp = f'{comp}, {stringfp} Million Metric Tons'
companycfp.append(compfp)
data = [{
'type': 'scattergeo',
'lon': longs,
'lat': lats,
'text': companycfp,
'marker': {
'size': [0.4*cp for cp in cfp],
'color': cfp,
'colorscale': 'fall',
},
}]
my_layout = Layout(title='How you measure up: Companies')
fig = {'data': data, 'layout': my_layout}
offline.plot(fig)
Plotly 网站代码;我不知道如何将上述数据添加到此视觉对象中。
import plotly.graph_objects as go
fig = go.Figure(go.Scattergeo())
fig.update_geos(projection_type="orthographic")
fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
非常感谢您的帮助!对不起,相当长的帖子。当谈到我尝试过的事情时,它并没有太多。我还没有找到很多关于我的情况的教程,到目前为止混合和匹配我的代码并没有很好地工作。
解决方案
- 让你的代码运行,我已经处理了一些相同的数据,我可以告诉你与你的数据相同的形状
- 由此 - 看来您正在做很多不必要的繁重工作。使用情节快递。先决条件是将您的数据放入数据框中。我相信这只是使用构造函数。
- 那么整体解决方案变得非常简单
解决方案
import plotly.express as px
px.scatter_geo(
pd.DataFrame(all_json_data),
lat="Latitude",
lon="Longitude",
color="carbonprint",
hover_data={"company": True, "carbonprint": ":.2f"},
).update_layout(geo={"projection":{"type":"orthographic"}})
让你的代码工作
import json
from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
import pandas as pd
import numpy as np
# filename = 'compPrint1.json'
# with open(filename) as f:
# all_json_data = json.load(f)
# readable_file = 'readable_json_data.json'
# with open(readable_file, 'w') as f:
# json.dump(all_json_data, f, indent=4)
all_json_data = {}
df2 = pd.read_html("https://www.latlong.net/category/cities-235-15.html")[0].rename(
columns={"Latitude": "Lat", "Longitude": "Lon"}
)
df2 = df2.rename(
columns={"Place Name": "company", "Lat": "Latitude", "Lon": "Longitude"}
).assign(carbonprint=np.random.uniform(1, 4, len(df2)), location=df2["Place Name"])
all_json_data = df2.to_dict("records")
# cfp = Carbon FootPrint
companies, cfp, locations, lats, longs = [], [], [], [], []
for json_data in all_json_data:
company = json_data["company"]
cp = json_data["carbonprint"]
location = json_data["location"]
lat = json_data["Latitude"]
long = json_data["Longitude"]
companies.append(company)
cfp.append(cp)
locations.append(location)
lats.append(lat)
longs.append(long)
companycfp = []
for json_data in all_json_data:
comp = json_data["company"]
fp = json_data["carbonprint"]
stringfp = str(fp)
compfp = f"{comp}, {stringfp} Million Metric Tons"
companycfp.append(compfp)
data = [
{
"type": "scattergeo",
"lon": longs,
"lat": lats,
"text": companycfp,
"marker": {
"size": [0.4 * cp for cp in cfp],
"color": cfp,
"colorscale": "fall",
},
}
]
my_layout = Layout(title="How you measure up: Companies")
fig = {"data": data, "layout": my_layout}
# offline.plot(fig)
go.Figure(fig)
推荐阅读
- javascript - 如果列表包含超过 25 个元素,则一次只取最新的 25 个元素
- docker - 如何设计 dockerfile 和 docker-compose 文件以适应属性文件中的动态 DB 细节变化?
- javascript - Django Form Javascript 读取布尔字段
- c# - 使用 Directory.EnumerateFiles()
- html - 带有单字符放置和突出显示的零件编号输入设计
- postgresql - 使用 PostgreSQL 查找平均停留时间
- android - Android Google Drive REST Api:重复文件
- python - 从两个不同的 Django 应用程序迁移两个不同的模型
- jenkins - Github PR 检查不禁止推送
- c - unsigned long vs uint64_t(性能影响)