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

Matplotlib折线图未延伸至网格边界问题求助

折线图未延伸至边框的解决方案

My line graph

我绘制的折线图未延伸至边框,而是起始位置滞后,且在网格终止线前就结束了。已查阅相关资料但未找到解决方案,以下是图表的代码:

plt.style.use("custom_style.mplstyle")
fig     = plt.figure(figsize=(16, 9), dpi=240)
ax      = fig.add_subplot(1, 7, (1, 6))
table   = fig.add_subplot(1, 7, 7)

# 删除表格列的网格线
table = plt.gca()
table.get_xaxis().set_visible(False)
table.get_yaxis().set_visible(False)
plt.box(on=None)

# 创建并缩放表格
CellColor = []
[CellColor.append(["#FFFFFF07"]) for row in range(stats.shape[0])]
theTable = table.table(cellText=stats.values, cellColours=CellColor, loc="center", cellLoc="left")
theTable.scale(1.4, 6)
theTable.set_fontsize(20)

color = "#52cc00" if float(dif) >= 0 else "#cc5240"
ax.plot_date(df["time"], df["close"], fmt=color, xdate=False, marker=None, linewidth=3, linestyle="-")

dateFMT = mdates.DateFormatter(r'%I%p')
ax.xaxis.set_major_formatter(dateFMT)
chart_name = name if isinstance(chart_name, pd.core.series.Series) else chart_name
ax.set_title(f"{chart_name}: {close} [{dif}%]", loc="left")

plt.savefig(f"charts/{name}.png")

custom_style.mplstyle的内容如下:

### FONT
text.color : white
font.family : Tahoma

### AXES
axes.facecolor      : FFFFFF07   # 坐标轴背景色
axes.edgecolor      : FFFFFF3D   # 坐标轴边缘色
axes.labelcolor     : FFFFFFD9

### TICKS
xtick.color          : FFFFFFD9      # 刻度标签颜色
ytick.color          : FFFFFFD9      # 刻度标签颜色

### GRIDS
grid.color       :   E6E6FA   # 网格线颜色
axes.grid : True
grid.linewidth : 0.4

### Legend
legend.facecolor     : inherit   # 图例背景色(inherit表示继承坐标轴背景色)
legend.edgecolor : FFFFFFD9 # 图例边缘色(inherit表示继承坐标轴边缘色)

### FIGURE
#TODO: notebook忽略此设置
figure.facecolor : 0C1C23    # 画布背景色
savefig.facecolor : 0C1C23    # 保存图片时的画布背景色
axes.titlepad : 12

### Title
axes.titlesize     : 25
axes.titlelocation : left

解决方法

问题根源在于plot_date的特殊处理逻辑,以及坐标轴自动范围的留白设置,按以下步骤修改即可:

  1. 替换plot_date为plot:你已经设置了xdate=False,直接使用plot可以避免plot_date针对日期轴的默认偏移处理,代码更直观:

    ax.plot(df["time"], df["close"], color=color, linewidth=3, linestyle="-")
    
  2. 强制x轴范围覆盖全部数据:手动设置x轴的最小和最大值,确保折线从数据的首尾点开始:

    ax.set_xlim(df["time"].min(), df["time"].max())
    
  3. 关闭x轴自动边距:消除坐标轴与数据之间的默认留白:

    ax.margins(x=0)
    

整合后的绘图部分代码如下:

color = "#52cc00" if float(dif) >= 0 else "#cc5240"
ax.plot(df["time"], df["close"], color=color, linewidth=3, linestyle="-")
ax.set_xlim(df["time"].min(), df["time"].max())
ax.margins(x=0)

dateFMT = mdates.DateFormatter(r'%I%p')
ax.xaxis.set_major_formatter(dateFMT)
chart_name = name if isinstance(chart_name, pd.core.series.Series) else chart_name
ax.set_title(f"{chart_name}: {close} [{dif}%]", loc="left")

修改后折线会完全延伸至坐标轴左右边框,与网格线对齐。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:03:15