下列的这个答案xmin
,我尝试删除和处的网格线xmax
,但失败了。这里缺少什么?
另外,如何输入变量xmin
和xmax
而不extra x ticks
需要手动输入数字?
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xtick={0,0.5,...,5},
xmin=0,xmax=5,
xmajorgrids,
major x grid style = {line width =2pt,dashed,black},
extra x ticks={0,5},
extra x tick labels={},
extra tick style={
grid=none,
},]
\addplot[mark=none,blue] {x^2};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
基本上这与以下答案相同符号 1但更加“自动化”,这意味着,你现在只需要一需要注意的地方是设置xmin
、xmax
和xtick distance
值。
% used PGFPlots v1.14
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
% =====================================================================
% state here the `xmin', `xmax' and `xtick distance' values
\pgfmathsetmacro{\xmin}{0}
\pgfmathsetmacro{\xmax}{5}
\pgfmathsetmacro{\DeltaX}{0.5}
% =====================================================================
% calculate the `xtick' positions without drawing the `xmajorgrid' at
% `xmin' and `xmax'
\pgfmathsetmacro{\xmintick}{\xmin + \DeltaX}
\pgfmathsetmacro{\nexttick}{\xmin + 2*\DeltaX}
\pgfmathsetmacro{\lasttick}{\xmax - \DeltaX}
\begin{axis}[
% set `xmin' and `xmax'
xmin=\xmin,
xmax=\xmax,
% set the `xtick' values using the defined variables
xtick={\xmintick,\nexttick,...,\lasttick},
xmajorgrids,
major x grid style={
dashed,
red,
},
% add the extra ticks without using the grid lines at `xmin' and `xmax'
% (for simplicity we can use the defined commands here ...
extra x ticks={\xmin,\xmax},
% % ... but since we have set these values explicitly we can also call
% % the values)
% extra x ticks={
% \pgfkeysvalueof{/pgfplots/xmin},
% \pgfkeysvalueof{/pgfplots/xmax}
% },
% set the style of the extra ticks
extra tick style={
% remove the grid
% by default the `extra tick style' is the same as for the "normal" ticks
grid=none,
},
]
\addplot [mark=none,blue] {x^2};
\end{axis}
\end{tikzpicture}
\end{document}
答案2
您几乎已经完成了:只需替换
xtick={0,0.5,...,5},
经过
xtick={0.5,1,...,4.5},
然后删除
extra x tick labels={},
编辑
OP 询问
为什么我的解决方案会这样失败
这种解决方法的想法基于一个事实:pgf图使用xtick
的位置绘制网格。因此,只要 和0
在5
内xtick
,它就会绘制线,并且它还会为0.5
、1
等绘制线1.5
。
我怎样才能在任何地方将“xmin”和“xmax”值调用为数值?
这是模棱两可的。如果你指的是用户已分配作为选项,(而不是通过计算的性质最小值/最大值pgf图),那么我相信可以通过 来访问\pgfkeysvalueof{/pgfplots/xmin}
。