[英]Plotly: How to annotate end of multiple lines with text and marker colors that match the lines?
The post Plotly: Annotate marker at the last value in line chart shows how to annotate end of lines with text and an individual marker.帖子Plotly:在折线图中的最后一个值处注释标记显示了如何使用文本和单个标记来注释行尾。 But how can you do the same thing for multiple lines and at the same time set the associated text and markers to match the color of all lines?
但是你怎么能对多行做同样的事情,同时设置相关的文本和标记来匹配所有行的颜色呢?
# 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()
You can address the features of each trace and build new traces for your end markers and text through:您可以通过以下方式处理每个跟踪的特征并为结束标记和文本构建新的跟踪:
for i, d in enumerate(fig.data):
fig.add_scatter(x=[d.x[-1]], y = [d.y[-1]], [...])
If you've specified colors when building your figure you can also retrieve trace colors and set colors for markers and fonts like this: If you've specified colors when building your figure you can also retrieve trace colors and set colors for markers and fonts like this:
textfont = dict(color=d.line.color),
marker = dict(color = d.line.color, size = 12)
The figure was being a bit crowded so I dropped one of the stocks.这个数字有点拥挤,所以我放弃了一只股票。 I also made room for the annotations by changing the position of the legend through
fig.layout.legend.x = -0.3
我还通过
fig.layout.legend.x = -0.3
更改图例的 position 为注释腾出空间
# 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),
showlegend=False)
fig.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.