如何为无实际日期的时间序列Plotly图表标注年份?
为无实际日期的Plotly时间序列图添加年份区分
你现有一份无实际日期的时间序列数据,仅包含无意义的index、rating和Year字段,已用Plotly绘制了基于index的折线图,以下是两种区分不同年份的实现方案:
方案1:添加垂直虚线分隔年份
先计算每个年份的最大index值作为年份分界点,再在图表中添加垂直虚线并标注年份:
import pandas as pd import plotly.express as px import plotly.graph_objects as go # 初始化数据 data = {'index': [1, 34, 78, 900, 1200, 5000, 9001, 12000, 15234, 23432], 'rating': [90, 85, 89, 82, 78, 65, 54, 32, 39, 45], 'Year': [2005, 2005, 2005, 2006, 2006, 2006, 2007, 2008, 2009, 2009]} df = pd.DataFrame(data) # 绘制基础折线图 fig = px.line(df, x='index', y='rating') # 获取每个年份的最大index(年份分界点)及年份列表 year_max_index = df.groupby('Year')['index'].max().tolist() years = df['Year'].unique().tolist() # 添加垂直虚线和年份标注 for idx, max_idx in enumerate(year_max_index[:-1]): # 最后一个年份无需添加分隔虚线 fig.add_vline( x=max_idx, line_dash="dash", line_color="gray", annotation_text=f"{years[idx+1]}", annotation_position="top right" ) fig.show()
方案2:添加交替灰色阴影区分年份
在每个年份对应的index区间添加交替深浅的灰色矩形阴影,同时标注年份:
import pandas as pd import plotly.express as px import plotly.graph_objects as go # 初始化数据 data = {'index': [1, 34, 78, 900, 1200, 5000, 9001, 12000, 15234, 23432], 'rating': [90, 85, 89, 82, 78, 65, 54, 32, 39, 45], 'Year': [2005, 2005, 2005, 2006, 2006, 2006, 2007, 2008, 2009, 2009]} df = pd.DataFrame(data) # 绘制基础折线图 fig = px.line(df, x='index', y='rating') # 获取每个年份的index区间(最小/最大index) year_ranges = df.groupby('Year')['index'].agg(['min', 'max']).reset_index() # 交替阴影颜色 colors = ['rgba(200,200,200,0.2)', 'rgba(230,230,230,0.2)'] # 添加阴影矩形(置于折线下方) for i, row in year_ranges.iterrows(): fig.add_shape( type="rect", x0=row['min'], x1=row['max'], y0=fig.layout.yaxis.range[0], y1=fig.layout.yaxis.range[1], fillcolor=colors[i % 2], line_width=0, layer="below" ) # 在每个区间上方添加年份标注 for i, row in year_ranges.iterrows(): fig.add_annotation( x=(row['min'] + row['max']) / 2, y=fig.layout.yaxis.range[1] * 1.02, text=f"{row['Year']}", showarrow=False ) fig.show()
内容的提问来源于stack exchange,提问作者user4740374
相关产品推荐
相关产品推荐

