First of all, let's start with changing title font size = 8. Then we will solve the issue related to legend size. For changing font-size = 8 Kindly refer to the Updated Code stated below:-
# 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)
I have used the same code provided by you. Now, We can move towards legends size.
So, According to me, you can't change legend size. You got bigger legend size due to defined Image Size. Current Image Size is squashing all layout.
There are 2 Solution which may help you:-
NOTE:- All the parameters related to position and size are expected. You can fill it up according to your requirements.
(1.) Plot Legend in horizontal Format:-
If you don't want to Change Image Size. Then you can try to plot legend in horizontal format. For doing this task reference code was given below:-
fig.update_layout(
# customize legend orientation & position
legend=dict(
title=None, orientation = 'h', y=1, yanchor="bottom", x=0.5, xanchor="center"
)
)
NOTE:- If you want to learn more about orientation, x, xanchor or more operation related to plotly legends then you can refer: Official Plotly Documentation
(2.) Change Image Size:-
If you want to change Image Size then you can refer code given below:-
# 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'}
)
and if it looks perfect then you can store it using the same size Using:-
# Store Image of Generated PLot
fig.write_image("../figures/vote_change_map.png", width = 600, height = 400)
Hope this Solution will be helpful to you.