表格中的 Pgfplot - 限制 x 域不起作用

表格中的 Pgfplot - 限制 x 域不起作用

我创建了以下图表: 在此处输入图片描述

使用此代码:

    \documentclass{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepgfplotslibrary{dateplot}
\pgfplotsset{compat=1.8}

%colors
\usepackage{color} % colors
\usepackage{xcolor} 
\definecolor{colourone}{RGB}{18,32,132} % 22,131,198
\definecolor{colourtwo}{RGB}{202,211,43}

\begin{document}

\pgfplotstableread[col sep=space]{
date donate volunteer Oxfam
2004 21.3 78.6 0
2005 21.9 76.1 0
2006 17.3 65.5 0
2007 17.2 57.2 0
2008 18.8 56.2 0
2009 18.7 57.5 0
2010 20.8 56.4 0
2011 20.9 50.8 0
2012 20.6 49.1 8.4
2013 21.4 47.8 7.6
2014 24.4 47.3 7.3
2015 24.3 46.0 6.3
2016 26.3 45.3 5.8
2017 29.4 45.9 5.8
2018 29.8 44.3 20.0
2019 30.8 45.8 5.2
2020 45.5 47.3 4.0
}\chart

\pgfplotsset{/pgfplots/ybar legend/.style={
        /pgfplots/legend image code/.code={%
            \draw[ ##1,/tikz/.cd,yshift=-0.25em]
            (0cm,0cm) rectangle (0.6em,0.6em);},},
}

\begin{tikzpicture}
\small
\begin{axis}[
ymajorgrids,
grid style = gray!30!white,
x=8.5mm,
bar width=3mm,
axis lines=left,
axis x line shift=0,
enlarge x limits=0,
enlarge y limits={0, upper},
%
% y ticks style and label
ylabel={Index},
ylabel shift = 1pt,
ymin=0,
ymax = 101,
ytick distance = 10,
axis y line*=right,
%y tick label style={/pgf/number format/.cd, fixed, fixed zerofill, precision=1, /tikz/.cd, font=\scriptsize},
%
% x axis ticks and style
xticklabel shift={0pt},
xtick=data,
xticklabels from table={\chart}{date},  
table/x expr = \coordindex,                     
x tick label style = {rotate=0},
%
% legends and labels
legend style = {fill = none, draw=none,
    legend columns=-1,
    at={(0.5,1.13)},
    anchor=north,
    /tikz/every even column/.append style={column sep=2em},
},
]
%
% done with the axis, now the plots   
\addplot [draw = black, mark = x] table [y=donate] {\chart};
\addlegendentry{Donate}; 
\addplot [draw = red, mark = x] table [y=volunteer] {\chart};
\addlegendentry{Volunteer};
\addplot [draw = gray, mark = x] table [y=Oxfam] {\chart};
\addlegendentry{Oxfam};
\end{axis}
\end{tikzpicture}

\end{document}

我想将乐施会地块的域名限制为 2012 年至 2020 年。我试过但restrict x to domain=2012:2020没有成功。我该如何实现?

答案1

因为您table/x expr = \coordindex在图中使用的实际 x 值是从 0 到 16,并且restrict x to domain适用于这些值。

选项:

  • restrict x to domain=8:16

  • \addplot [draw = gray, mark = x, x filter/.expression={\thisrow{date}>2011 ? x : nan}] table [y=Oxfam] {\chart};

    x filter将根据数据表中的实际值进行过滤。

  • table/x expr = \coordindex从选项中删除axis,并使用restrict x to domain您建议的设置。(我可能会使用xtick distance=1,xticklabel style={/pgf/number format/set thousands separator=}它而不是xtick=data从表中读取刻度标签,但就您而言,您得到的是相同的。)

相关内容