You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GraphRAG(NetworkX)绘图X轴刻度标签不显示问题求助

NetworkX时间线图X轴日期刻度标签不显示的解决方法

问题描述

我花费数小时尝试在基于NetworkX的时间线绘图中显示X轴的日期刻度标签,以下是与实际代码类似的示例,但运行后X轴刻度始终不显示。当前绘图效果如下:

当前绘图效果

问题根源

NetworkX的draw_networkx_nodes、draw_networkx_edges等绘图函数会自动调整坐标轴的显示范围,覆盖了原本的日期轴范围设置,导致Matplotlib无法正确识别并渲染日期刻度。

修复后的完整代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct  3 23:04:11 2025
"""
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import date2num
from datetime import datetime, timedelta

# STEP 1: Create dummy data
num_entries = 10
start_time = datetime(2025, 10, 1, 8, 0)

data = {
    "From_dt": [start_time + timedelta(hours=4 * i) for i in range(num_entries)],
    "Description": [f"Entry {i}" for i in range(num_entries)],
    "Category": ["100 Advance" if i % 2 == 0 else "Other" for i in range(num_entries)]
}

df = pd.DataFrame(data)

# STEP 2: Create graph
G = nx.DiGraph()
for i, row in df.iterrows():
    G.add_node(i, timestamp=row["From_dt"], text=row["Description"], category=row["Category"])
    if i > 0:
        G.add_edge(i - 1, i, type="time")

# STEP 3: Generate position dictionary using date2num
pos = {i: (date2num(df.loc[i, "From_dt"]), -i) for i in df.index}

# STEP 4: Plot
fig, ax = plt.subplots(figsize=(12, 6))

# Draw edges and nodes
nx.draw_networkx_edges(G, pos, ax=ax, edge_color="gray", arrows=True)
colors = ["green" if G.nodes[i]["category"] == "100 Advance" else "orange" for i in G.nodes]
nx.draw_networkx_nodes(G, pos, ax=ax, node_color=colors, node_size=100)

# Draw labels every few nodes to avoid clutter
step = max(1, len(df) // 5)
labels = {i: df.loc[i, "Category"] for i in range(0, len(df), step)}
nx.draw_networkx_labels(G, pos, labels, font_size=9, ax=ax)

# --- 关键修改:手动设置X轴范围,确保日期刻度能被正确识别 ---
x_min = date2num(df["From_dt"].min())
x_max = date2num(df["From_dt"].max())
ax.set_xlim(x_min - 0.1, x_max + 0.1)  # 增加少量边距,避免刻度被截断

# 基础轴标签与标题设置
ax.set_xlabel("日期与时间")
ax.set_ylabel("条目索引")
ax.set_title("带日期X轴的极简时间线图")
ax.grid(True)

# 配置X轴日期刻度
ax.xaxis_date()
from matplotlib.dates import AutoDateLocator, AutoDateFormatter

locator = AutoDateLocator()
formatter = AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

# 调整底部边距,避免刻度标签被遮挡
plt.subplots_adjust(bottom=0.3)

# 旋转刻度标签,提升可读性
fig.autofmt_xdate(rotation=45)

# 自定义鼠标悬停显示格式
def format_coord(x, y):
    try:
        return f"x = {mdates.num2date(x).strftime('%d-%b %H:%M')}, y = {y:.1f}"
    except Exception:
        return f"x = {x:.2f}, y = {y:.1f}"
ax.format_coord = format_coord

# 显示绘图
plt.show()

核心修改说明

  1. 移除无效锚定绘图:原代码中ax.plot(..., alpha=0)无法阻止NetworkX调整坐标轴范围,直接删除即可。
  2. 手动锁定X轴范围:在绘制完NetworkX的节点和边之后,手动设置X轴的范围为日期数据的最小和最大值(额外增加少量边距),确保Matplotlib能识别到完整的日期区间并渲染刻度。
  3. 调整配置顺序:将X轴范围设置放在NetworkX绘图操作之后,避免被其自动调整逻辑覆盖。

内容的提问来源于stack exchange,提问作者Hugh L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 06:14:51