我想用 PGF/TikZ 为我的出版物制作图表。我需要手动格式化日期刻度(参见 Matplotlib 文档中的示例)。
我定义了一个开始日期(xmin
)和一个结束日期(xmax
);在这两者之间,我想要安排主要刻度(间隔 24 个月)和次要刻度(每个月)。
我请求您的帮助,并希望有人已经解决了这个问题并愿意在这里分享。
梅威瑟:
\documentclass[11pt, tikz, crop, varwidth=250mm, border=2mm]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepgfplotslibrary{fillbetween}
\usepgfplotslibrary{dateplot}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
% LEGEND %
legend style = {at={(0.9,0.9)}, legend columns=3, anchor=east, font=\tiny, draw=none, inner sep =0pt},
%
tick label style={font=\small},
label style={font=\small},
title style={font=\small},
%
width = 8.0cm, height = 6cm,
%
tick style={thin},
minor tick style ={thin},
%
date coordinates in = x,
xticklabel=\year-\month,
date ZERO = 2021-01-01,
xmin = 2021-01-01,
xmax = 2023-12-01,
xticklabel style = {anchor=north east, rotate=45},
%
% I don't want do manually "bake" the ticks into the plot
xtick={2021-01-01, 2021-07-01, 2022-01-01, 2022-07-01, 2023-01-01, 2023-07-01, 2023-12-01},
%
ylabel = {Distance},
ymin=-0, ymax=6,
ytick={0, 1.0, ..., 6.0},
xtick pos=bottom,ytick pos=left,
]
\addplot[color=black, solid, thick]
table[x=date, y=value, col sep=comma]{data.txt};
\addlegendentry{data}
\end{axis}
\end{tikzpicture}
\end{document}
数据:
\begin{filecontents*}{data.txt}
date, value
2021-01-01, 2.072457
2021-02-01, 2.209934
2021-03-01, 2.588002
2021-04-01, 2.498113
2021-05-01, 2.214694
2021-06-01, 2.242065
2021-07-01, 2.197125
2021-08-01, 1.948843
2021-09-01, 1.945804
2021-10-01, 2.077016
2021-11-01, 2.501014
2021-12-01, 2.813076
2022-01-01, 2.848438
2022-02-01, 2.994862
2022-03-01, 3.425982
2022-04-01, 3.744854
2022-05-01, 3.407557
2022-06-01, 3.402444
2022-07-01, 3.748655
2022-08-01, 3.529377
2022-09-01, 3.733859
2022-10-01, 3.890095
2022-11-01, 3.357926
2022-12-01, 3.468896
2023-01-01, 3.689547
2023-02-01, 3.976246
2023-03-01, 3.889607
2023-04-01, 3.884615
2023-05-01, 4.281348
2023-06-01, 4.085681
2023-07-01, 4.429838
2023-08-01, 4.700875
2023-09-01, 4.960294
2023-10-01, 5.18179
2023-11-01, 5.327941
2023-12-01, 5.459256
\end{filecontents*}
答案1
我希望这有帮助!
\begin{document}
\begin{tikzpicture}
\begin{axis}[
% LEGEND %
legend style = {at={(0.9,0.9)}, legend columns=3, anchor=east, font=\tiny, draw=none, inner sep =0pt},
%
tick label style={font=\small},
label style={font=\small},
title style={font=\small},
%
width = 8.0cm, height = 6cm,
%
tick style={thin},
minor tick style ={thin},
%
date coordinates in = x,
xticklabel=\year-\month,
date ZERO = 2021-01-01,
xmin = 2021-01-01,
xmax = 2024-01-01,
xticklabel style = {anchor=north east, rotate=45},
%
%%%%% the changes %%%%%%
minor x tick num=24,
xtick distance=365,
%%%%%%%%%%%%%%%%%%%%%%%%
ylabel = {Distance},
ymin=-0, ymax=6,
ytick={0, 1.0, ..., 6.0},
xtick pos=bottom,ytick pos=left,
]
\addplot[color=black, solid, thick]
table[x=date, y=value, col sep=comma]{data.txt};
\addlegendentry{data}
\end{axis}
\end{tikzpicture}
\end{document}