Python Plotly:在折线图中的最后一个值处注释标记
我想在plotly express python中用一个大红点标记折线图的最后一个值,有人能帮我吗 我成功地构建了折线图,但无法注释点 下面是我的dataframe,我希望对dataframe中的最后一个值进行注释 下面是创建的折线图,我希望我的图表类似于屏幕截图中的第二幅图像 我正在使用的代码:Python Plotly:在折线图中的最后一个值处注释标记,python,annotations,plotly,linechart,plotly-python,Python,Annotations,Plotly,Linechart,Plotly Python,我想在plotly express python中用一个大红点标记折线图的最后一个值,有人能帮我吗 我成功地构建了折线图,但无法注释点 下面是我的dataframe,我希望对dataframe中的最后一个值进行注释 下面是创建的折线图,我希望我的图表类似于屏幕截图中的第二幅图像 我正在使用的代码: fig = px.line(gapdf, x='gap', y='clusterCount', text="clusterCount") fig.show() 您可以将最后一
fig = px.line(gapdf, x='gap', y='clusterCount', text="clusterCount")
fig.show()
您可以将最后一个数据点的附加轨迹与
plotly.graph\u objects
叠加,有关示例,请参见下面的代码
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
gapdf = pd.DataFrame({
'clusterCount': [1, 2, 3, 4, 5, 6, 7, 8],
'gap': [-15.789, -14.489, -13.735, -13.212, -12.805, -12.475, -12.202, -11.965]
})
fig = px.line(gapdf, x='gap', y='clusterCount')
fig.add_trace(go.Scatter(x=[gapdf['gap'].iloc[-1]],
y=[gapdf['clusterCount'].iloc[-1]],
text=[gapdf['clusterCount'].iloc[-1]],
mode='markers+text',
marker=dict(color='red', size=10),
textfont=dict(color='green', size=20),
textposition='top right',
showlegend=False))
fig.update_layout(plot_bgcolor='white',
xaxis=dict(linecolor='gray', mirror=True),
yaxis=dict(linecolor='gray', mirror=True))
fig.show()
gflavia的建议非常有效。 但您也可以通过直接寻址图中的元素而不是像这样的数据源来设置额外的跟踪和关联文本:
fig.add_scatter(x = [fig.data[0].x[-1]], y = [fig.data[0].y[-1]])
地块1
完整代码:
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
gapdf = pd.DataFrame({
'clusterCount': [1, 2, 3, 4, 5, 6, 7, 8],
'gap': [-15.789, -14.489, -13.735, -13.212, -12.805, -12.475, -12.202, -11.965]
})
fig = px.line(gapdf, x='gap', y='clusterCount')
fig.add_scatter(x = [fig.data[0].x[-1]], y = [fig.data[0].y[-1]],
mode = 'markers + text',
marker = {'color':'red', 'size':14},
showlegend = False,
text = [fig.data[0].y[-1]],
textposition='middle right')
fig.show()