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

使用pgfplots绘图时图形在x=5处截断,已设xmax=6,求原因

问题分析与解决

你的图形在x=5处看似截断,主要由两个问题导致:

1. 函数值超出y轴范围被裁剪

你设置了ymin=-4,但当x=6时,目标函数的计算结果为:

-0.5*(6)^2 + 2*6 + 1 = -18 + 12 + 1 = -5

该值低于ymin=-4,超出y轴显示范围,被默认开启的clip=true裁剪。从x≈5.8开始,函数值就会低于-4,因此图形在接近x=6的位置消失,视觉上像是截断在x=5。

2. x=6的刻度标签被隐藏

你设置的xtick={-3,...,6}包含x=6的刻度,但对应的xticklabels={,-2,-1,,1,2,3,4,5,}最后一个元素为空值,导致x=6的刻度标签不显示,容易让你误以为坐标轴只到x=5。


修正后的代码

\documentclass{standalone}
\usepackage[utf8]{inputenc}
\usepackage{tikz,pgfplots}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=newest, width=7cm, height=7cm,
  layers/axis lines on top/.define layer set={
    axis background,
    axis grid,
    axis ticks,
    pre main,
    main,
    axis lines,
    axis descriptions,
    axis foreground,
    axis tick labels,
  }{/pgfplots/layers/standard},
axis on top=false,
every x tick label/.append style={font=\footnotesize, yshift=0.2ex},
every y tick label/.append style={font=\footnotesize, xshift=0.2ex}}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ clip=true, set layers=axis lines on top,
xmin=-3, xmax=6,
ymin=-5, % 调整y轴下限,容纳x=6处的函数值
ymax=5,
xtick={-3,...,6},
xticklabels={,-2,-1,,1,2,3,4,5,6}, % 添加上x=6的刻度标签
ytick={-4,...,5},
yticklabels={,-3,-2,-1,,1,2,3,4,},
minor tick num=1,
axis lines=middle,
xlabel=$x$,
ylabel=$y$,
every axis plot/.append style={ultra thick},
xmajorgrids=true,
xminorgrids=true,
ymajorgrids=true,
yminorgrids=true,
]
\addplot[line width=1.5pt, color=black, samples=100]{-0.5*x^2+2*x+1};
\node[anchor=north west, fill=gray!50] at (rel axis cs:0,1) {\textbf{3}};
\draw(current axis.south west)rectangle(current axis.north east);
\end{axis}
\end{tikzpicture}
\end{document}

额外建议

如果无需手动定制刻度标签,可直接删除xticklabels和yticklabels两行,让pgfplots自动生成对应刻度的标签,避免手动设置时出现遗漏或数量不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:00:31