pythonplotlychoropleth

Adjust the size of the text label in Plotly


I'm trying to adjust the text size according to country size, so the text will be inside the boarders of the country. Here's my code:

# imports
import pandas as pd
import plotly.express as px

# uploading file
df=pd.read_csv('regional-be-daily-latest.csv', header = 1)

# creating figure
fig = px.choropleth(df, locations='Code', color='Track Name')
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

fig.add_scattergeo(

  locations = df['Code'],
  text = df['Track Name'],
  mode = 'text',
)

fig.show()

The output visualization that my code gives me is:

enter image description here

The text label for the orange country is inside the boarders of the country but the text to label the blue country is bigger than the country itself.

What I'm looking for would be to adjust the size so it will not exceed the boarders of the country. How can I do this?


Solution

  • You can set the font size using the update_layout function and specifying the font's size by passing the dictionary in the font parameter.

    import pandas as pd
    import plotly.express as px
    
    df=pd.read_csv('regional-be-daily-latest.csv', header = 1)
    
    fig = px.choropleth(df, locations='Code', color='Track Name')
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
    
    fig.add_scattergeo(
    
      locations = df['Code'],
      text = df['Track Name'],
      mode = 'text',
    )
    
    
    fig.update_layout(
        font=dict(
            family="Courier New, monospace",
            size=18,  # Set the font size here
            color="RebeccaPurple"
        )
    )
    
    fig.show()