我正在使用 Plotly 制作分区统计图。但是,地理地图看起来很小。
我的代码在这里:
fig = px.choropleth(df,
geojson=geojson,
locations="Capitalize",
featureidkey="properties.name",
color="Scale",
hover_name='Capitalize',
hover_data=['Quantity'],
animation_frame="Period",
projection="mercator",)
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(title_text = 'Product A',
autosize=True,
hovermode='closest',
title_x = 0.5,
margin={"r":0,"t":100,"l":0,"b":0},
geo=dict(showframe = False, showcoastlines = False))
宽度和高度属性并没有完全达到我想要的效果。我只想放大地理地图。我怎样才能在情节中做到这一点?
我也有同样的问题。我发现了这个相关问题,其中写着:
Plotly 尝试占用所有可用空间而不改变 图像比例。如果你的 div 很宽,就会有很多空白 左右有空间,但会从上到下填充 底部。
我增加了布局的
height
。我从这里开始:
fig.update_layout(margin=dict(l=0, r=0, b=0, t=0),
width=1500)
对此:
fig.update_layout(margin=dict(l=0, r=0, b=0, t=0),
width=1500,
height=800)
这极大地改善了我的图像尺寸。
这仍然在我的地图周围留下了相当大的空白。我通过计算边界框而不是使用
fitbounds
来改进这一点。我使用辅助模块 turfpy
来计算几何体的边界框,使用 pip install turfpy
安装。
from turfpy.measurement import bbox
from functools import reduce
def compute_bbox(gj):
gj_bbox_list = list(
map(lambda f: bbox(f['geometry']), gj['features']))
gj_bbox = reduce(
lambda b1, b2: [min(b1[0], b2[0]), min(b1[1], b2[1]),
max(b1[2], b2[2]), max(b1[3], b2[3])],
gj_bbox_list)
return gj_bbox
gj_bbox = compute_bbox(gj)
fig = px.choropleth(fdf,
geojson=gj,
locations=locationcol,
color=datacol,
color_continuous_scale="Viridis",
range_color=(0, max_value),
featureidkey=key,
scope='europe',
hover_data=[namecol, 'LAD11NM']
)
fig.update_geos(
# fitbounds="locations",
center_lon=(gj_bbox[0]+gj_bbox[2])/2.0,
center_lat=(gj_bbox[1]+gj_bbox[3])/2.0,
lonaxis_range=[gj_bbox[0], gj_bbox[2]],
lataxis_range=[gj_bbox[1], gj_bbox[3]],
visible=False,
)
您需要手动计算地图的边界框。这是一种无需导入
turfpy
即可完成此操作的方法,按照 最佳答案 的要求。
假设您的
geojson
文件名为“geojson”,请将此代码添加到对 px.choropleth()
的调用下方:
min_lon = min(i[0] for c in geojson['features'] for i in c['geometry']['coordinates'][0])
max_lon = max(i[0] for c in geojson['features'] for i in c['geometry']['coordinates'][0])
min_lat = min(i[1] for c in geojson['features'] for i in c['geometry']['coordinates'][0])
max_lat = max(i[1] for c in geojson['features'] for i in c['geometry']['coordinates'][0])
fig.update_geos(
visible=False,
lataxis_range=[min_lat, max_lat],
lonaxis_range=[min_lon, max_lon],
)
您可能还需要将
width
和 height
参数传递给 px.choropleth()
和/或 fig.update_layout()
。
查看 Plotly 的网站,然后向下滚动到 fitbounds 部分。
我相信你的问题可能是代码
fig.update_geos(fitbounds="locations", visible=False)
您需要将“locations”部分更改为其他内容,例如“geojson”或“False”。
希望这有效!