Plotly Python实现X轴双标签(周与月)的时间可视化咨询
用Plotly实现周/月双层X轴的时间序列可视化
完全可以用Python的Plotly实现这种双层X轴的效果,核心思路是通过叠加X轴,将月份作为上层标签、周作为下层标签,对应到数据的时间维度上。以下是具体实现代码和说明:
实现步骤
- 整理数据集:确保数据包含周、月的标识字段,以及对应的数值指标。
- 创建主数据轨迹:以周为单位绘制时间序列数据。
- 配置双层X轴:下层显示周标签,上层显示月份标签,对应到每个月的起始周位置。
完整代码示例
import plotly.graph_objects as go import pandas as pd import numpy as np # 构造模拟数据集(替换成你的真实数据即可) dates = pd.date_range(start='2024-01-01', end='2024-03-31', freq='W') df = pd.DataFrame({ 'date': dates, 'week': [f"周{w}" for w in dates.isocalendar().week], 'month': dates.month_name(), 'value': np.random.randint(10, 50, size=len(dates)) }) # 提取每个月的起始周对应的索引位置 month_start_indices = [df[df['month'] == m].index[0] for m in df['month'].unique()] month_names = df['month'].unique() # 创建图表 fig = go.Figure() # 添加主数据轨迹 fig.add_trace(go.Scatter( x=df.index, y=df['value'], mode='lines+markers', line={'color': '#2c3e50'}, marker={'size': 8}, name='每周数值' )) # 配置下层X轴(周标签) fig.update_xaxes( tickmode='array', tickvals=df.index, ticktext=df['week'], title_text='周', tickfont={'size': 10} ) # 配置上层X轴(月标签) fig.update_layout( xaxis2=dict( tickmode='array', tickvals=month_start_indices, ticktext=month_names, overlaying='x', side='top', title_text='月', tickfont={'size': 12, 'color': '#e74c3c'}, showgrid=False # 隐藏上层轴网格线,避免干扰 ), title='周&月双层X轴时间序列图', yaxis_title='数值', height=500, width=800 ) fig.show()
代码说明
- 数据适配:模拟数据生成了2024年1-3月的每周数据,包含周、月标识和随机数值,你可以直接替换为自己的真实数据集。
- 双层轴逻辑:下层X轴绑定每条数据的索引,显示对应的周标签;上层X轴通过
overlaying='x'叠加在主X轴上方,仅在每个月的起始周位置显示月份名称,避免标签重叠。 - 样式优化:通过
tickfont设置不同轴的字体样式,showgrid=False隐藏上层轴网格线,让图表更清晰易读。
内容的提问来源于stack exchange,提问作者Lukas Tomek
相关产品推荐
相关产品推荐

