我正在try 创建一张美国 map ,根据覆盖在 map 上的值和特定位置点,使用Chloropeth填充各州.假设数据如下:

data = {'state_code': ['AZ', 'NY', 'IL', 'CA'],
    'lat': [33.44838, 40.7648, 41.8842, 34.052235],
    'lon': [-112.07404, -73.935242, -87.6324, -118.243398],
    'count': [2,7,5,5 ]
    }
df = pd.DataFrame(data)

Count是我想用来填充州的变量,我想用点来映射城市的经度和纬度.

这就是我try 过的:

fig = go.Figure()

fig.add_trace(
px.choropleth(df,
                locations='state_code', 
                locationmode="USA-states", 
                scope="usa",
                color='count',
                color_continuous_scale="viridis",                 
                ))
fig.add_trace(
px.scatter_geo(df, 
           lon = df['lon'],
           lat = df['lat'],
           mode = 'markers',
           marker_color = "Red",
           ))
fig.update_layout(
    title = 'Title'
)

fig.show()

我得到以下错误:

ValueError: 
Invalid element(s) received for the 'data' property of 
    Invalid elements include: [Figure({
'data': [{'coloraxis': 'coloraxis',
          'geo': 'geo',
          'hovertemplate': 'state_code=%{location}<br>count=%{z}<extra></extra>',
          'locationmode': 'USA-states',
          'locations': array(['AZ', 'NY', 'IL', 'CA'], dtype=object),
          'name': '',
          'type': 'choropleth',
          'z': array([2, 7, 5, 5], dtype=int64)}],
'layout': {'coloraxis': {'colorbar': {'title': {'text': 'count'}},
                         'colorscale': [[0.0, '#440154'], [0.1111111111111111,
                                        '#482878'], [0.2222222222222222,
                                        '#3e4989'], [0.3333333333333333,
                                        '#31688e'], [0.4444444444444444,
                                        '#26828e'], [0.5555555555555556,
                                        '#1f9e89'], [0.6666666666666666,
                                        '#35b779'], [0.7777777777777778,
                                        '#6ece58'], [0.8888888888888888,
                                        '#b5de2b'], [1.0, '#fde725']]},
           'geo': {'center': {}, 'domain': {'x': [0.0, 1.0], 'y': [0.0, 1.0]}, 'scope': 'usa'},
           'legend': {'tracegroupgap': 0},
           'margin': {'t': 60},
           'template': '...'}})]

The 'data' property is a tuple of trace instances
that may be specified as:
  - A list or tuple of trace instances
    (e.g. [Scatter(...), Bar(...)])
  - A single trace instance
    (e.g. Scatter(...), Bar(...), etc.)
  - A list or tuple of dicts of string/value properties where:
    - The 'type' property specifies the trace type
        One of: ['bar', 'barpolar', 'box', 'candlestick',
                 'carpet', 'choropleth', 'choroplethmapbox',
                 'cone', 'contour', 'contourcarpet',
                 'densitymapbox', 'funnel', 'funnelarea',
                 'heatmap', 'heatmapgl', 'histogram',
                 'histogram2d', 'histogram2dcontour', 'icicle',
                 'image', 'indicator', 'isosurface', 'mesh3d',
                 'ohlc', 'parcats', 'parcoords', 'pie',
                 'pointcloud', 'sankey', 'scatter',
                 'scatter3d', 'scattercarpet', 'scattergeo',
                 'scattergl', 'scattermapbox', 'scatterpolar',
                 'scatterpolargl', 'scattersmith',
                 'scatterternary', 'splom', 'streamtube',
                 'sunburst', 'surface', 'table', 'treemap',
                 'violin', 'volume', 'waterfall']

    - All remaining properties are passed to the constructor of
      the specified trace type

    (e.g. [{'type': 'scatter', ...}, {'type': 'bar, ...}])

推荐答案

正如@Sarah Messer回答的那样,不可能在图形对象上覆盖快速 map ,因此该 map 在图形对象中以另一种格式提供. 具体地说,以下代码将实现这一点.

fig = go.Figure()
fig.add_trace(go.Choropleth(
                locations=df['state_code'], 
                locationmode="USA-states", 
                z=df['count'],
                colorscale="viridis",                 
                ))

fig.add_trace(go.Scattergeo(
    lon = df['lon'],
    lat = df['lat'],
    mode = 'markers',
    marker_color = "red",
    hovertemplate='%{lon},%{lat}<extra></extra>',
))

fig.update_layout(
    autosize=True,
    height=450,
    title = 'Title',
    geo=dict(
        scope='usa'
    )
)

fig.show()

enter image description here

Python相关问答推荐

大Pandas 胚胎中产生组合

将特定列信息移动到当前行下的新行

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

更改键盘按钮进入'

根据二元组列表在pandas中创建新列

两个pandas的平均值按元素的结果串接元素.为什么?

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

如何从列表框中 Select 而不出错?

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

Flash只从html表单中获取一个值

未调用自定义JSON编码器

numpy.unique如何消除重复列?

在pandas/python中计数嵌套类别

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

如何在Python中将超链接添加到PDF中每个页面的顶部?

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

如何使用加速广播主进程张量?

来自Airflow Connection的额外参数

如何在Pandas中用迭代器求一个序列的平均值?