Plotly Geoscatter with Aggregation:以悬停方式显示聚合

2024-09-26 18:06:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试用Plotly创建一个Geoscatter图,其中标记大小应该指示一个城市(zip_city)中的客户数(行项目)。我的代码基于Plotly文档中的两个模板:United States Bubble Map和聚合部分Mapping with Aggregates。你知道吗

我成功地编写了一个代码,实现了我想要的功能,除了一个缺点:当我将鼠标悬停在泡沫上时,我希望看到城市的名称加上客户的数量(聚合的结果),所以类似于Aguadilla: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)

更新:

我可以直接在data参数中访问transforms参数的结果来显示每个城市的客户数吗?你知道吗


Tags: 代码importcitydfdata客户ascustomer
1条回答
网友
1楼 · 发布于 2024-09-26 18:06:57

您可以创建一个包含所需内容的列表,然后在data中设置text=list。也不要忘记指定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)  

相关问题 更多 >

    热门问题