【问题标题】:Plotly : How to enable text label in line graph for the last value?剧情 |为最后一个值启用折线图中的文本标签
【发布时间】:2021-12-12 20:45:22
【问题描述】:

我正在尝试构建一个图表,其中折线图应仅以某种漂亮的格式显示最后一个元素的值。

line graph with no text at end

现在文本的当前方法显示所有元素,并且是直接文本,与同一图表中的不同线产生大量冲突并且看起来很笨拙。

实现如下图所示的目标会非常好。

desired line graph with text

【问题讨论】:

  • this 能解决您的问题吗?
  • 感谢@vestland 的回答,这确实显示了最后一行的文本,但现在又产生了一个问题,那就是它创建了一个新的散点图,因此当我尝试隐藏这些行时从图例中,由于分散而生成的点仍然存在。我需要一种方法,这样当我通过图例隐藏一条线时,它也会隐藏点。

标签: python-3.x plotly plotly-dash


【解决方案1】:

现在通过以下方式处理:

legendgroup = d.name

情节 1:全部

情节2:在图例中取消选择GOOG,看到标记也消失了:

完整代码:

# 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2015-09-25
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多