python - Plotly Geoscatter with Aggregation:在悬停信息中显示聚合
问题描述
我一直在尝试使用 Plotly 创建一个 Geoscatter 图,其中标记大小应指示一个城市中的客户(行项目)数量(zip_city
)。我的代码基于 Plotly 文档中的两个模板:United States Bubble Map和聚合部分Mapping with Aggregates。
我设法编写了一个可以满足我要求的代码,除了一个缺点:当我将鼠标悬停在气泡上时,我希望看到城市名称加上客户数量(聚合的结果),所以类似于阿瓜迪亚:2。你能帮我怎么做吗?
这是我的代码(作为 plotly 的初学者,我也愿意改进代码):
import plotly.offline as pyo
import pandas as pd
df = pd.DataFrame.from_dict({'Customer': [111, 222, 555, 666],
'zip_city': ['Aguadilla', 'Aguadilla', 'Arecibo', 'Wrangell'],
'zip_latitude':[18.498987, 18.498987, 18.449732,56.409507],
'zip_longitude':[-67.13699,-67.13699,-66.69879,-132.33822]})
data = [dict(
type = 'scattergeo',
locationmode = 'USA-states',
lon = df['zip_longitude'],
lat = df['zip_latitude'],
text = df['Customer'],
marker = dict(
size = df['Customer'],
line = dict(width=0.5, color='rgb(40,40,40)'),
sizemode = 'area'
),
transforms = [dict(
type = 'aggregate',
groups = df['zip_city'],
aggregations = [dict(target = df['Customer'], func = 'count', enabled = True)]
)]
)]
layout = dict(title = 'Customers per US City')
fig = dict( data=data, layout=layout )
pyo.plot( fig, validate=False)
更新:
我可以transforms
直接在data
参数中访问参数的结果以显示每个城市的客户数量吗?
解决方案
您可以创建一个列表,其中包含您想要的内容,然后text=list
在data
. 也不要忘记指定hoverinfo='text'
。
我更新了你的代码,所以试试这个:
import pandas as pd
import plotly.offline as pyo
df = pd.DataFrame.from_dict({'Customer': [111, 222, 555, 666],
'zip_city': ['Aguadilla', 'Aguadilla', 'Arecibo', 'Wrangell'],
'zip_latitude':[18.498987, 18.498987, 18.449732,56.409507],
'zip_longitude':[-67.13699,-67.13699,-66.69879,-132.33822]})
customer = df['Customer'].tolist()
zipcity = df['zip_city'].tolist()
list = []
for i in range(len(customer)):
k = str(zipcity[i]) + ':' + str(customer[i])
list.append(k)
data = [dict(
type = 'scattergeo',
locationmode = 'USA-states',
lon = df['zip_longitude'],
lat = df['zip_latitude'],
text = list,
hoverinfo = 'text',
marker = dict(
size = df['Customer'],
line = dict(width=0.5, color='rgb(40,40,40)'),
sizemode = 'area'
),
transforms = [dict(
type = 'aggregate',
groups = df['zip_city'],
aggregations = [dict(target = df['Customer'], func = 'count', enabled = True)]
)]
)]
layout = dict(title = 'Customers per US City')
fig = dict(data=data, layout=layout)
pyo.plot(fig, validate=False)
推荐阅读
- python - 在 Pandas DataFrame 中查找两个匹配的行以计算值
- flutter - 从 api 检索 json 的主体
- reactjs - ReactJS,检查 this.state 和 nextState 之间的区别
- php - 为什么在 php 中尝试使用 curl 使用 json 时,我得到一个空结果?
- javascript - React 事件处理程序的闭包是否可以使我的组件免于不必要的重新渲染?
- google-apps-script - 读取特定电子表格中的独立 Google Apps 脚本
- c++ - 将大型堆栈分配数组作为函数参数传递会导致堆栈溢出
- android - 如何在 App 主视图上添加边框半径?
- sql - 根据前一行值选择列
- c# - 在 MVC 下实现的 Blazor 组件未呈现