首先,让我们从更改title font size = 8 开始。然后我们将解决与legend size相关的问题。如需更改font-size = 8,请参阅以下更新的代码:-
# Import all the Libraries
from urllib.request import urlopen
import plotly.express as px
import json
# Open JSON File Using 'urlopen' Module of 'json' library and used 'json.load()' JSON Loader to load JSON Data
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
# Used Mapbox choropleth map, each row of 'data_frame (df)' is represented by a colored region on a Mapbox map.
fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='vote_change',
color_continuous_scale="magma",
range_color=(-25, 35),
mapbox_style="carto-positron",
zoom=2, center = {"lat": 37.0902, "lon": -95.7129},
opacity=0.75,
labels={'total_votes_2016':'TEST'}
)
# Updated Layout for 'Title with Font Size 8' and 'Narrower Legend'
fig.update_layout(
title='Figure 2: Change in Turnout from 2016 to 2020',
margin=dict(l=0, r=0, t=40, b=0),
font=dict(size=8),
)
# Show Plotted Figure
fig.show()
# Store Image of Generated Plot
fig.write_image("../figures/vote_change_map.png", width = 450, height = 250)
我使用了您提供的相同代码。现在,我们可以前往legends size。
所以,根据我的说法,您无法更改 legend size。由于定义了图像大小,您得到了bigger legend size。当前图像大小正在挤压所有布局。
有两个解决方案可以帮助你:-
注意:- 所有与position 和size 相关的参数都是预期的。您可以根据自己的要求填写。
(1.) 以horizontal 格式绘制图例:-
如果您不想更改图像大小。然后您可以尝试以horizontal 格式绘制legend。下面给出了执行此任务的参考代码:-
fig.update_layout(
# customize legend orientation & position
legend=dict(
title=None, orientation = 'h', y=1, yanchor="bottom", x=0.5, xanchor="center"
)
)
注意:-如果您想了解更多关于orientation、x、xanchor或更多与plotly legends相关的操作,可以参考:Official Plotly Documentation
(2.) 更改图像大小:-
如果你想改变Image Size,那么你可以参考下面给出的代码:-
# Added 'width=600' and 'height=400' in Current Code for Ploting Chroleopath Mapbox
fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='vote_change',
width=600, height=400,
color_continuous_scale="magma",
range_color=(-25, 35),
mapbox_style="carto-positron",
zoom=2, center = {"lat": 37.0902, "lon": -95.7129},
opacity=0.75,
labels={'total_votes_2016':'TEST'}
)
如果它看起来很完美,那么您可以使用相同的size 存储它使用:-
# Store Image of Generated PLot
fig.write_image("../figures/vote_change_map.png", width = 600, height = 400)
希望此解决方案对您有所帮助。