Sunday, November 17, 2024
Google search engine
HomeLanguagesPlotly – How to show legend in single-trace scatterplot with plotly express?

Plotly – How to show legend in single-trace scatterplot with plotly express?

In this article let’s see how to show legend in single-trace scatterplot with plotly express. A ‘trace’ is the name given to each plot inside the chart. Generally in plotly legend is not visible for single trace scatter plots.

Example:

In the below, example packages and data are imported and a single trace scatter plot is plotted using px.scatter(). fig.layout.showlegend= True doesn’t work in this case so we need to enable showlegend by using this code fig[‘data’][0][‘showlegend’]=True. fig[‘data’][0][‘name’]=’Humidity’ says that name of the only variable in the legend is ‘Humidity’. 

To view and download the CSV file used click here

Python3




# import packages and libraries
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
import plotly.express as px
  
# reading the dataset
df = pd.read_csv('weather.csv', encoding='UTF-8')
  
# creating a scatterplot
fig = px.scatter(df, x="Temperature", y='Humidity',
                 trendline='ols', trendline_color_override='red')
  
  
fig['data'][0]['showlegend'] = True
fig['data'][0]['name'] = 'Humidity'
  
fig.show()


Output:

Before setting legend

After setting legend.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments