Reputation: 13746
With a plotly express line chart of multiple lines, how would you change the default legend heading 'variable' seen below, as well as the hover text also shown below, to show a semantic name rather than the text 'variable'?
In other words, lets say that what you are plotting is lines each describing some quantity about a certain data class, and you'd like the text 'class' to appear instead of the generic default text 'variable'. Both (a) as the legend title as well as when hovering data points.
Upvotes: 0
Views: 1172
Reputation: 61204
1. If possible, rename your dataset, and if not:
2. change the legend title and the hovertemplate for each trace using:
names = {'variable':'class'}
fig.for_each_trace(lambda t: t.update(hovertemplate = t.hovertemplate.replace('variable', names['variable'])))
fig.update_layout(legend_title_text = names['variable'])
In order to be sure, you'd have to provide a dataset and a code snippet to reproduce your problem. For now, I can only guess that you've got a dataset of a long form, and that you've used px.line
to build a figure. I'll use px.scatter
since that produces the same result, but also for a dataset that is too small to produce a line plot.
So, the reason why 'variable'
is displayed is most likely because you've got a dataset that contains the name 'variable'
.
import plotly.express as px
import pandas as pd
import numpy as np
df = pd.DataFrame({'variable': ['gold', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
'index': [192]*10,
'value': list(np.arange(1,11))})
fig = px.scatter(df, x = 'index', y = 'value', color = 'variable')
fig.show()
Therefore, the most straight-forward way to fix your problem would be to rename your dataset:
import plotly.express as px
import pandas as pd
import numpy as np
df = pd.DataFrame({'class': ['gold', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
'index': [192]*10,
'value': list(np.arange(1,11))})
fig = px.scatter(df, x = 'index', y = 'value', color = 'class')
fig.show()
If that does not work for your real-life challange, you can always change these attributes directly in your figure object using:
fig.for_each_trace(lambda t: t.update(hovertemplate = t.hovertemplate.replace('variable', names['variable'])))
fig.update_layout(legend_title_text = names['variable'])
import plotly.express as px
import pandas as pd
import numpy as np
df = pd.DataFrame({'variable': ['gold', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
'index': [192]*10,
'value': list(np.arange(1,11))})
fig = px.scatter(df, x = 'index', y = 'value', color = 'variable')
names = {'variable':'class'}
fig.for_each_trace(lambda t: t.update(hovertemplate = t.hovertemplate.replace('variable', names['variable'])))
fig.update_layout(legend_title_text = names['variable'])
fig.show()
Upvotes: 1