我正在做这个tikzpicture
:
\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0,
ymax=1,
xtick=data,
xticklabels={$1$, $2$, $3$, $4$, $5$, $6$},
xlabel={Die Face},
ylabel={Probability},
title={Probability Distribution of a Six-Sided Die},
bar width=1pt, % Adjust the width of the bars
nodes near coords, % Display the explicit values near the bars
every node near coord/.append style={
font=\footnotesize,
align=center,
anchor=west,
yshift=5pt,
/pgf/number format/.cd,
fixed,
fixed zerofill,
precision=1,
frac
}, % Customize the appearance of the values
]
\addplot[fill=black!40,draw=black,line width=1pt] coordinates {
(1, 1/6)
(2, 1/6)
(3, 1/6)
(4, 1/6)
(5, 1/6)
(6, 1/6)
};
\end{axis}
\end{tikzpicture}
但分数...嗯...显示得有点丑。老实说,我不知道这是怎么回事...我只希望有$\frac{1}{6}$,而不是这个奇怪的分子和分母。
答案1
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0,
ymax=1,
xtick=data,
xticklabels={$1$, $2$, $3$, $4$, $5$, $6$},
xlabel={Die Face},
ylabel={Probability},
title={Probability Distribution of a Six-Sided Die},
bar width=1pt, % Adjust the width of the bars
nodes near coords, % Display the explicit values near the bars
every node near coord/.append style={
font=\footnotesize,
align=center,
anchor=west,
yshift=7pt, % Adjust as needed
},
point meta=explicit symbolic % This line tells TikZ to use the provided labels directly
]
\addplot[fill=black!40,draw=black,line width=1pt] coordinates {
(1, 1/6) [${\frac{1}{6}}$]
(2, 1/6) [${\frac{1}{6}}$]
(3, 1/6) [${\frac{1}{6}}$]
(4, 1/6) [${\frac{1}{6}}$]
(5, 1/6) [${\frac{1}{6}}$]
(6, 1/6) [${\frac{1}{6}}$]
};
\end{axis}
\end{tikzpicture}
\end{document}
meta=explicit
我在轴选项中添加了 point symbolic 。这告诉 TikZ[...]
直接使用方括号中提供的标签。 中的坐标\addplot command
现在包含格式为 的每个点的明确标签[${\frac{1}{6}}$]
。这些标签将直接用作节点文本,确保分数正确显示为\frac{1}{6}
。
答案2
您可以使用例如frac shift=3
手册第 1056 页
/pgf/数字格式/frac shift={⟨整数⟩}(无默认值,初始为 4)
如果您因为稳定性问题而遇到问题,请尝试使用不同的小数移位。移位值 k 越高,对不准确数据或不准确算术的敏感度就越高。从技术上讲,会发生以下情况。如果 r < 1 是尾数的小数部分,则计算比例 i = 1/r · 10k,其中 k 是移位;忽略 i 的小数部分。值 1/r 是内部计算的,其误差会被放大。如果您仍然遇到稳定性问题,请在序言中使用 \usepackage{fp}。然后,frac 样式将自动采用更高的绝对精度 fp 来计算 1/r。
\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0,
ymax=1,
xtick=data,
xticklabels={$1$, $2$, $3$, $4$, $5$, $6$},
xlabel={Die Face},
ylabel={Probability},
title={Probability Distribution of a Six-Sided Die},
bar width=1pt, % Adjust the width of the bars
nodes near coords, % Display the explicit values near the bars
every node near coord/.append style={
font=\footnotesize,
align=center,
anchor=west,
yshift=5pt,
/pgf/number format/.cd,
fixed,
fixed zerofill,
precision=1,
frac,
frac shift=3,
}, % Customize the appearance of the values
]
\addplot[fill=black!40, draw=black, line width=1pt] coordinates {
(1, 1/6)
(2, 1/6)
(3, 1/6)
(4, 1/6)
(5, 1/6)
(6, 1/6)
};
\end{axis}\end{tikzpicture}
\end{document}