Customize Legend of plotly Graph in Python (Example)

 

Hello again! In this tutorial, I will show you how you can customize the legend of your plotly graph in the Python programming language.

This time, we are also going to make use of the Python pandas library, which is used for manipulating data in Python. We shall use it to create the dataset that we are going to visualize and customize in plotly.

With just a few lines of code, I will show you how you can make your graph legend look and feel the way you want it to.

Here is what we will go through in this tutorial:

Without any further ado, let’s start writing some code!

 

Install and Load plotly and pandas

In this tutorial, we are going to build a plotly barplot. But before we can build our plotly barplot, we first need to install both the plotly and the pandas libraries. In your preferred Python IDE, run the following lines of code one after the other:

pip install plotly
pip install pandas

The above lines of code will install both plotly and pandas, along with their respective dependencies. Next, we will need to import both libraries. This we can do by running the lines of code below:

import plotly.express as px
import pandas as pd

With the plotly and pandas libraries installed and loaded in our Python IDE, we are now ready to build a barplot. First, though, we need a dataset, which is why we are going to create one.

 

Create Dataset

We will make use of the pandas DataFrame() function to create a dataset. Please run the code below to create and print the dataset:

df = pd.DataFrame({"Students":["James","Sheila","Max","Anna","Jenny","Harry"],
                   "Sex":["Male","Female","Male","Female","Female","Male"],
                   "Age":[24,20,25,23,18,27]})
print(df)
#   Students   Sex    Age
# 0    James    Male   24
# 1   Sheila  Female   20
# 2      Max    Male   25
# 3     Anna  Female   23
# 4    Jenny  Female   18
# 5    Harry    Male   27

As you can see, it is very easy to create a dataset in pandas. Let’s now go on to build our barplot from this dataset.

 

Build plotly Barplot

Building a barchart is very easy. Just run the following lines of code:

fig = px.bar(df,
             x = "Students",
             y = "Age",
             color = "Sex")
fig.show()

What have we just done? We have just plotted the students on the X axis against their ages on the Y axis, so that we can see in a graphical format how old each student is and make comparisons.

So, with a few lines of code, we have built an interactive plotly barplot in Python. The bargraph is colored by “Sex”, so we can clearly distinguish male students from female students; and when you hover over the barchart, you can see information about each student in the dataset. Now, let us see how we can customize the plot legend to make it more appealing.

 

Customize plotly Barplot Legend

We are going to make some modifications to the legend of the barplot we built in the previous section. For example, we will move the legend to the top left corner of our graph, with a horizontal orientation, then we will change the font of the legend title, then place the legend in a box, and then give it a background color, border color, and border width. Let’s do it:

fig = px.bar(df,
             x = "Students",
             y = "Age",
             color = "Sex")
 
fig.update_layout(legend = dict(orientation = "h",
                                x=0,
                                y=1,
                                title_font_family="Sitka Small",
                                bgcolor="LightBlue",
                                bordercolor="Black",
                                borderwidth=2))

In the above code, we set the legend orientation to horizontal, represented by the letter “h” in the fig.update.layout() function. Next, we used the x and y coordinates to move the legend to the top left corner of the graph. We then set the legend title font to Sitka Small, gave it a background color of light blue, and set the legend text box border color to black, with a width of 2. Let us see what that looks like

fig.show()

There you have it! We have just customized the legend of our plotly barplot in Python. You can definitely play around with the parameters in the fig.update.layout() function to change the appearance of your plot legend. For instance, you could change the legend title font to Times New Roman or Arial Black and the increase or decrease the border width as you please.

With this, I hope you have learned how to build a plotly barplot in Python and how to modify or customize its legend.

If you found this tutorial helpful in your learning, then make sure to watch out for more tutorials like this here on the Statistics Globe website.

Thanks, and I will see you in the next one!

 

Video, Further Resources & Summary

Do you need more explanations on how to build interactive plotly visualizations in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain how to build a barchart with plotly in Python.

 

The YouTube video will be added soon.

 

Furthermore, you could have a look at some of the other tutorials on Statistics Globe:

This post has shown how to customize the legend of a plotly graph in Python. In case you have further questions, you may leave a comment below.

 

R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top