我必须制作一个在间隔标签处有刻度的图(不在标签之间的线段中间)。下图中预期的变化用红色标记。顺便问一句:是否存在一种自动写入刻度的方法(不是通过明确写入每个点xtick={1838,1843,etc.}
)?MWE:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=1838,
xmax=1862,
x tick label as interval,
xticklabel={
\pgfmathprintnumber\tick\discretionary{--}{--}{--}\pgfmathparse{\nexttick-1}\pgfmathprintnumber\pgfmathresult
},
xtick={1838,1843,1848,1853,1858,1863},
xticklabel style={
align=center,
text width=1cm,
execute at begin node=\setlength{\baselineskip}{8pt},
rotate=90,
anchor=east
},
xmajorgrids,
]
\addplot
table[row sep=crcr]{%
1840 8\\
1845 7\\
1850 6\\
1855 4\\
1860 4\\
};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
这是一个使用该pgfplotstable
包的功能的解决方案。
这样就可以计算表中两个条目之间的偏移量,假设这些条目间距均匀。然后使用偏移量来虚拟计算和排版,而\nexttick
无需调用x ticklabels as interval
。xtick
还定义了以xtick=data
避免手动输入。
有两点我不太确定:
- 价值观
xticklabels
- y 轴上的红色十字
\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\begin{document}
% Get number of rows
\pgfplotstableread[row sep=crcr]{
1840 8\\
1845 7\\
1850 6\\
1855 4\\
1860 4\\
}\loadedtable
% Row amount of the source table
\pgfplotstablegetrowsof{\loadedtable}
\pgfmathtruncatemacro{\numrows}{\pgfplotsretval}
% Number of last row (numbering starts at 0)
\pgfmathtruncatemacro{\lastrow}{\numrows-1}
% First value in data
\pgfplotstablegetelem{0}{[index]0}\of{\loadedtable}
\pgfmathsetmacro{\databegin}{\pgfplotsretval}
% Last value in data
\pgfplotstablegetelem{\lastrow}{[index]0}\of{\loadedtable}
\pgfmathsetmacro{\dataend}{\pgfplotsretval}
% Data step (assumes uniform step)
\pgfmathsetmacro{\datashift}{(\dataend-\databegin)/(\numrows-1)}
\begin{tikzpicture}
\begin{axis}[
xticklabel={\pgfmathprintnumber{\tick}\discretionary{--}{--}{--}\pgfmathparse{\tick+\datashift-1}\pgfmathprintnumber\pgfmathresult},
xtick=data,
xticklabel style={
align=center,
text width=1cm,
execute at begin node=\setlength{\baselineskip}{8pt},
rotate=90,
anchor=east,
%yshift={\xticklabelyshiftcoeff*\pgfkeysvalueof{/pgfplots/width}}
},
y tick label as interval,
xmajorgrids,
enlarge x limits=false,
clip marker paths=false,
]
\addplot table {\loadedtable};
\end{axis}
\end{tikzpicture}
\end{document}