Matplotlib折线图未延伸至网格边界问题求助
折线图未延伸至边框的解决方案

我绘制的折线图未延伸至边框,而是起始位置滞后,且在网格终止线前就结束了。已查阅相关资料但未找到解决方案,以下是图表的代码:
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的特殊处理逻辑,以及坐标轴自动范围的留白设置,按以下步骤修改即可:
替换
plot_date为plot:你已经设置了xdate=False,直接使用plot可以避免plot_date针对日期轴的默认偏移处理,代码更直观:ax.plot(df["time"], df["close"], color=color, linewidth=3, linestyle="-")强制x轴范围覆盖全部数据:手动设置x轴的最小和最大值,确保折线从数据的首尾点开始:
ax.set_xlim(df["time"].min(), df["time"].max())关闭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
相关产品推荐
相关产品推荐

