Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to manually add a legend color and legend font size on...

How to manually add a legend color and legend font size on a plotly figure in Python?

In this article, we will learn how to manually add a legend color and legend font size on a plotly figure in Python. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes.

Here we will discuss different methods for manually adding legend color and legend font size in plotly express, using two different examples for each to make it more clear.

Example 1: In this Bar chart, We are adding the legend color and legend font size using fig.update_layout() method, legend_font_color=”red” – this parameter allows you to set the fontcolor whereas legend_font_size= 19 – this parameter allows you to set the fontsize.

Python3




# importing packages
import plotly.express as px
  
# using medals_wide dataset
wide_df = px.data.medals_wide()
  
# plotting the bar chart
fig = px.bar(wide_df, x="nation", y=[
             "gold", "silver", "bronze"],
             title="GeeksforLazyroar")
  
# set legend color
fig.update_layout(legend_font_color="red")
  
# set font size
fig.update_layout(legend_font_size=19)
  
# showing figure.
fig.show()


Output:

Example 2: In this Scatter chart, We are adding the legend color and legend font size using fig.update_layout() method, legend_font_color=”gold” – this parameter allows you to set the fontcolor whereas legend_font_size= 10 – this parameter allows you to set the fontsize.

Python3




# importing packages
import plotly.express as px
  
# using the gapminder dataset
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="sex",
                 symbol="smoker", facet_col="time",
                 labels={"sex": "Gender", "smoker": "Smokes"})
  
# set legend color
fig.update_layout(legend_font_color="gold")
  
# set font size
fig.update_layout(legend_font_size=10)
  
fig.show()


Output:

RELATED ARTICLES

Most Popular

Recent Comments