plotly

Change the Legend Size in Plotly

A legend is defined as a key that accompanies a specific plot provided with extra information either by color, labels, or symbols. It is mainly expressed as a box holding the metadata about the plot. It is very useful to easily navigate and interpret the data presented in a specific plot.

When working with Plotly, you will need to customize the legend properties such as size, background color, font size, and more.

In this tutorial, we will show you how to customize the legend size of the plots using Plotly.

Let’s get started.

Plotly Update_Layout()

One of the most useful functions in the Plotly ecosystem is the update_layout() function. It allows us to customize the plots in a wide range of properties. Therefore, it is no doubt that we use this function to customize the legend properties.

Let us see how we can use this function to customize the legend.

Showing the Legend

Before we dive into how to resize the legend, let’s start by creating a figure showing the legend.

For this tutorial, we use the gapminder() data provided in the Plotly express. The code is as shown in the following:

import plotly.express as px

df = px.data.gapminder().query("year==2007")
fig = px.scatter(df, x='gdpPercap', y='pop', color='continent', size='pop', size_max=50)
fig.update_layout(showlegend=True)

In this example, we create a simple scatter plot using the gapminder() data. Using the update_layout() function, we tell Plotly to display the legend by setting the showlegend parameter to True.

The resulting figure is as shown:

We can see the legend on the top right side of the figure.

Customizing the Legend Size

The best way to customize the size of the legend in Plotly is by customizing the size of the legend items.

This is because Plotly uses a dynamic sizing depending on the item size. For example, to shrink the size of the legend, we can set the fonts of the legend to a smaller font.

An example is as shown in the following:

fig.update_layout(showlegend=True, legend=dict(
    title_font_family='Courier New',
    font=dict(
        size=8
    )
))

In this case, we modify the value of the legend title_font_family to ‘Courier New’ and set the font size of the items to 8. This shrinks the legend as shown in the following figure:

Keep in mind that customizing the size of the legend may lead to a poor visibility on smaller screens.

Conclusion

This short article covers how you can customize the size of the legend in Plotly using the update_layout() function and the legend parameter.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list