是否可以告诉pgfplots
放置勾号标签之间刻度线代替在刻度线?
梅威瑟:
\documentclass[margin=5pt]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=5in,
height=3in,
axis lines=middle,
scaled ticks=false,
xtick=\empty,
xmin=0,
xmax=3,
extra x ticks={0,1,2,3},
extra x tick labels={low,high,med},
]
\addplot [mark=*,draw] coordinates {(0.5,2) (1.5,4) (2.5,3)};
\end{axis}
\end{tikzpicture}
\end{document}
结果:
我可以通过添加来手动完成
xticklabel style = {xshift=1.9cm,align=center},
但这似乎不能令人满意、不可靠,并且需要太多的反复试验。
答案1
怎么样
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=5in,
height=3in,
axis lines=middle,
scaled ticks=false,
xtick=\empty,
xmin=0,
xmax=3,
xtick={0,1,2,3},
xticklabel=\empty,
extra x ticks={0.5,1.5,2.5},
extra x tick labels={low,high,med},
extra x tick style={major tick length=0pt}
]
\addplot [mark=*,draw] coordinates {(0.5,2) (1.5,4) (2.5,3)};
\end{axis}
\end{tikzpicture}
\end{document}
答案2
x tick label as interval
正是您想要的,但问题是axis lines=middle
刻度位置 0 默认被忽略并且不生成刻度,因此只有两个刻度间隔而不是三个,因此第一个标签(“低”)丢失。
我的解决方案是使用extra x ticks
来提供缺失的间隔和标签,但借助 来阻止显示多余的刻度style
。
\documentclass[margin=5pt]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=5in,
height=3in,
axis lines=middle,
scaled ticks=false,
xmin=0,
xmax=3,
x tick label as interval,
xtick={1,2,3},
xticklabels={high,med},
% first label would be missing w/o the lines below
extra x ticks={0.1, 0.9},
extra x tick labels={low},
extra x tick style={
tick style={draw=none}
},
]
\addplot [mark=*,draw] coordinates {(0.5,2) (1.5,4) (2.5,3)};
\end{axis}
\end{tikzpicture}
\end{document}