[英]Plotly: How to change variable/label names for the legend in a plotly express line chart?
[英]plotly express line chart, renaming "variable" in legend title and hover text?
1.如果可能,重命名您的数据集,如果没有:
2.使用以下方法更改每个跟踪的图例标题和悬停模板:
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'])
为了确定,您必须提供数据集和代码片段来重现您的问题。 现在,我只能猜测您有一个长格式的数据集,并且您已经使用px.line
构建了一个图形。 我将使用px.scatter
,因为它会产生相同的结果,但也适用于太小而无法生成线图的数据集。
因此,显示'variable'
的原因很可能是因为您有一个包含名称'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()
因此,解决问题的最直接方法是重命名数据集:
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()
如果这对您的现实挑战不起作用,您始终可以使用以下方法直接在您的图形对象中更改这些属性:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.