如何从 pgfplots 更改箱线图的颜色?黑色会很棒!以下是 MWE:
\documentclass{scrartcl}
\usepackage{pgfplots}
\usepgfplotslibrary{statistics}
\begin{document}
\begin{tikzpicture}
\begin{axis}[y=1cm, try min ticks=2]
\addplot+[boxplot]
table[row sep=\\,y index=0] {
data\\
1\\ 2\\ 1\\ 5\\ 4\\ 10\\
7\\ 10\\ 9\\ 8\\ 9\\ 9\\
21\\
};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
要获得完全黑色的箱线图(包括异常值的标记),最简单的方法是使用\addplot [mark=*, boxplot]
(请注意省略了+
)。 的作用+
是向 PGFPlots 指示您想要使用绘图循环列表定义的样式:默认情况下,第一个绘图为蓝色,第二个绘图为红色,依此类推。然而,这不是您在本例中想要的。通过省略+
,PGFPlots 将恢复为基本绘图选项:黑线,无标记。通过添加mark=*
,您可以指定要为异常值使用的标记。
\documentclass{scrartcl}
\usepackage{pgfplots}
\usepgfplotslibrary{statistics}
\begin{document}
\begin{tikzpicture}
\begin{axis}[y=1cm, try min ticks=2]
\addplot [mark=*, boxplot]
table[row sep=\\,y index=0] {
data\\
1\\ 2\\ 1\\ 5\\ 4\\ 10\\
7\\ 10\\ 9\\ 8\\ 9\\ 9\\
21\\
};
\end{axis}
\end{tikzpicture}
\end{document}
答案2
以防万一有人(像我一样)想知道如何为箱线图分别设置填充和边框颜色,这里有一个执行此操作的示例(借用自我的博客):
\documentclass{standalone}
\usepackage{pgfplots}
% Nice color sets, see see http://colorbrewer2.org/
\usepgfplotslibrary{colorbrewer}
% initialize Set1-4 from colorbrewer (we're comparing 4 classes),
\pgfplotsset{compat = 1.15,
cycle list/Set1-8}
% Tikz is loaded automatically by pgfplots
\usetikzlibrary{pgfplots.statistics, pgfplots.colorbrewer}
% provides \pgfplotstabletranspose
\usepackage{pgfplotstable}
\usepackage{filecontents}
\begin{filecontents*}{data.csv}
22, 26, 30, 17, 45
10, 15, 13, 12, 17
12, 30, 6, 57, 10
33, 38, 36, 25, 24
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\pgfplotstableread[col sep=comma]{data.csv}\csvdata
% Boxplot groups columns, but we want rows
\pgfplotstabletranspose\datatransposed{\csvdata}
\begin{axis}[
boxplot/draw direction = y,
x axis line style = {opacity=0},
axis x line* = bottom,
axis y line = left,
enlarge y limits,
ymajorgrids,
xtick = {1, 2, 3, 4},
xticklabel style = {align=center, font=\small, rotate=60},
xticklabels = {Apples, Oranges, Bananas, Melons},
xtick style = {draw=none}, % Hide tick line
ylabel = {Juiciness},
ytick = {20, 40}
]
\foreach \n in {1,...,4} {
\addplot+[boxplot, fill, draw=black] table[y index=\n] {\datatransposed};
}
\end{axis}
\end{tikzpicture}
\end{document}