我是 LaTeX 的初学者,想用它来处理工业文档。我想知道是否有办法只改变下面图中一个条的颜色,即“TestDetails”,以说明它是一个本地宏而不是 LaTeX 关键字。我一直在尝试使用点元,但找不到方法。
\documentclass{article}
\usepackage{filecontents}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{width=.95\textwidth, compat=newest}
\begin{document}
\begin{filecontents}{data.csv}
{Occurences}, {keyword}
215, item
159, SI
134, subsubsection
106, TestDetails
58, caption
\end{filecontents}
\pgfplotstableread[col sep=comma]{data.csv}{\datatable}
\begin{tikzpicture}
\begin{axis}[
/pgf/number format/.cd,1000 sep={},
width=0.8\linewidth,height=6cm,
xbar,
xmin=30, xmax=250,
xtick=\empty,
enlarge x limits={value=0.1, upper},
enlarge y limits=0.1,
ytick=data,
y dir=reverse,
xlabel= {},
y tick label style={major tick length=0pt},
yticklabels from table={\datatable}{[index]1},
nodes near coords, nodes near coords align=horizontal,
]
\addplot [draw,fill=blue!50]table[
y expr=\coordindex,
x index=0]{\datatable};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
您无法更改单个条形的颜色,但可以添加第二个条形的颜色,\addplot
过滤掉您想要突出显示的所有条形。
这里有两种样式discard if
和discard if not
,它们接受两个参数:表中列的名称和要突出显示的值。请注意,您需要将数据文件本身提供给\addplot
,它不适用于使用创建的表\pgfplotstableread
,并且您需要使用xtick={<list>}
而不是xtick=data
,否则您的标签将不同步。
\documentclass{standalone}
\usepackage{filecontents}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{width=.95\textwidth, compat=newest}
\pgfplotsset{
discard if/.style 2 args={
x filter/.code={
\edef\tempa{\thisrow{#1}}
\edef\tempb{#2}
\ifx\tempa\tempb
\def\pgfmathresult{inf}
\fi
}
},
discard if not/.style 2 args={
x filter/.code={
\edef\tempa{\thisrow{#1}}
\edef\tempb{#2}
\ifx\tempa\tempb
\else
\def\pgfmathresult{inf}
\fi
}
}
}
\begin{document}
\begin{filecontents}{data.csv}
{Occurences}, {keyword}
215, item
159, SI
134, subsubsection
106, TestDetails
58, caption
\end{filecontents}
\pgfplotstablegetrowsof{data.csv}
\edef\numberofrows{\pgfplotsretval}
\begin{tikzpicture}
\begin{axis}[
/pgf/number format/.cd,1000 sep={},
width=0.8\linewidth,height=6cm,
xbar,/pgf/bar shift=0pt,
xmin=0, xmax=250,
xtick=\empty,
enlarge x limits={value=0.1, upper},
enlarge y limits=0.1,
ytick={0,...,\numberofrows},
y dir=reverse,
xlabel= {},
y tick label style={major tick length=0pt},
yticklabels from table={data.csv}{[index]1},
nodes near coords, nodes near coords align=horizontal
]
\addplot [draw,fill=blue!50,discard if={keyword}{TestDetails}
] table [
y expr=\coordindex,
x index=0,col sep=comma
]{data.csv};
\addplot [draw,fill=orange,discard if not={keyword}{TestDetails}] table [
y expr=\coordindex,
x index=0,col sep=comma
]{data.csv};
\end{axis}
\end{tikzpicture}
\end{document}