帖子Plotly:在折线图中最后一个值处注释标记 显示了如何使用文本和单个标记注释行尾。但是,如何对多行执行相同的操作,同时设置关联的文本和标记以匹配所有行的颜色?
# imports
import pandas as pd
import plotly.express as px
# data
df = px.data.stocks()
colors = px.colors.qualitative.T10
# plotly
fig = px.line(df,
x = 'date',
y = [c for c in df.columns if c != 'date'],
template = 'plotly_dark',
color_discrete_sequence = colors,
title = 'Stocks',
)
fig.show()
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式处理每个跟踪的功能并为结束标记和文本构建新的跟踪:
for i, d in enumerate(fig.data):
fig.add_scatter(x=[d.x[-1]], y = [d.y[-1]], [...])
Run Code Online (Sandbox Code Playgroud)
如果您在构建图形时指定了颜色,您还可以检索迹线颜色并为标记和字体设置颜色,如下所示:
textfont = dict(color=d.line.color),
marker = dict(color = d.line.color, size = 12)
Run Code Online (Sandbox Code Playgroud)
这个数字有点拥挤,所以我放弃了其中一只股票。我还通过更改图例的位置来为注释腾出空间fig.layout.legend.x = -0.3
# imports
import pandas as pd
import plotly.express as px
# data
df = px.data.stocks()
df = df.drop('AMZN', axis = 1)
colors = px.colors.qualitative.T10
# plotly
fig = px.line(df,
x = 'date',
y = [c for c in df.columns if c != 'date'],
template = 'plotly_dark',
color_discrete_sequence = colors,
title = 'Stocks',
)
# move legend
fig.layout.legend.x = -0.3
# add traces for annotations and text for end of lines
for i, d in enumerate(fig.data):
fig.add_scatter(x=[d.x[-1]], y = [d.y[-1]],
mode = 'markers+text',
text = d.y[-1],
textfont = dict(color=d.line.color),
textposition='middle right',
marker = dict(color = d.line.color, size = 12),
legendgroup = d.name,
showlegend=False)
fig.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2377 次 |
| 最近记录: |