数据框列存在NaN时如何为Plotly图表添加推文悬停信息?
Plotly图表悬停提示展示推文内容问题及解决方案
问题描述
现有7000余行小时级加密货币行情数据,其中仅139行存在标注为content的推文内容,剩余行content列值为NaN。希望在Plotly绘制的行情图表中,将对应时间点的推文内容添加到数据点的悬停信息中。
最初使用的实现代码如下:
fig = px.line(total_data, x = total_data.date, y = total_data.doge_close) fig.add_trace( go.Scatter( x=total_data[total_data.has_tweet==1].date, y=total_data[total_data.has_tweet == 1]['doge_close'], mode = 'markers', hovertemplate = '<i>tweet:</i>'+ '<br>' + '<i>%{text}</i>', text = [t for t in total_data['content']], name = 'has_tweets')) fig.show()
运行后悬停提示的推文位置显示为NaN,无法正常展示对应时间点的实际推文内容。content列可通过以下代码模拟生成:
df = px.data.stocks().set_index('date')[['GOOG']].rename(columns={'GOOG':'values'}) df['has_tweet'] = df['tweet'].apply(lambda x: 0 if x != x else 1) df['tweet'] = random.choices(['A tweet','Longer tweet', 'emoji','NaN'], weights=(5,10,5,80), k=len(df))
通用问题复现代码:
import plotly.express as px import plotly.graph_objects as go import random fig = px.line(df, x=df.index, y = 'values') fig.add_trace(go.Scatter(x=df[df.has_tweet==1].index, y = df[df.has_tweet==1]['values'], mode = 'markers', hovertemplate = '<i>tweet:</i>'+ '<br>' + '<i>%{text}</i>', text = [t for t in df['tweet']], name = 'has_tweets')) fig.show()
解决方案
问题核心原因是散点图层仅使用了has_tweet==1的过滤后数据,但text参数传入了全量数据的content列,导致数据长度不匹配、悬停内容错位。修改text参数的取值范围,仅传入过滤后有推文的行对应的content值即可修复问题,修复后代码如下:
fig = px.line(total_data, x = total_data.date, y = total_data.doge_close) fig.add_trace(go.Scatter(x=total_data[total_data.has_tweet==1].date, y=total_data[total_data.has_tweet==1]['doge_close'], mode = 'markers', hovertemplate = '<i>tweet:</i>'+ '<br>' + '<i>%{text}</i>', text = [t for t in total_data.loc[total_data['has_tweet']==1, 'content']], name = 'has_tweets')) fig.show()
运行后即可在对应数据点的悬停提示中正常展示推文内容。
内容的提问来源于stack exchange,提问作者jd_h2003
相关产品推荐
相关产品推荐

