如何在python plotly库中使用choropleth map函数按洲可视化?

2024-06-10 02:19:15 发布

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

我正试图创建一个choropleth地图,以便从数据帧中可视化每个大陆的总页面浏览量,但plotly library函数的locationmode参数没有该地图。有没有办法解决此问题?当我将“国家名称”用于locationmode时,它不起作用

st.subheader("Continent's Total Pageviews Choropleth Map")
fig2 = go.Figure(data= go.Choropleth(
locations= df1['continent'],
z = df1['total_pageviews'].astype(float),
locationmode = 'country names',
colorscale = 'Reds',
colorbar_title = "Total Pageviews",
))
fig2.update_layout( width = 1100 , height = 500 )
st.write(fig2)

Tags: 数据go可视化地图页面totaldf1st
1条回答
网友
1楼 · 发布于 2024-06-10 02:19:15
  • 获取大陆的地理信息
  • 构建一个geopandas数据框架,集成页面视图数据
  • 简单映射框绘图
import requests
import geopandas as gpd
import numpy as np
import plotly.express as px

cont = requests.get(
    "https://gist.githubusercontent.com/hrbrmstr/91ea5cc9474286c72838/raw/59421ff9b268ff0929b051ddafafbeb94a4c1910/continents.json"
)
gdf = gpd.GeoDataFrame.from_features(cont.json())

gdf = gdf.assign(
    total_pageviews=np.random.randint(10 ** 7, 10 ** 9, len(gdf))
).set_index("CONTINENT")

px.choropleth_mapbox(
    gdf,
    geojson=gdf.geometry,
    locations=gdf.index,
    color="total_pageviews",
    mapbox_style="carto-positron",
    color_continuous_scale="Reds",
    opacity=0.5,
    zoom=1,
).update_layout(margin={"l": 0, "r": 0, "b": 0, "t": 0})

相关问题 更多 >