我正在尝试创建一个概率直方图,这是它的当前状态
\documentclass[oneside,english]{amsart}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ ybar, ymin=0, ymax=0.6, xlabel={$k$}, ylabel={$\mathbb{P}
(Z_2=k)$}, xtick={0,...,7}, ytick={0,0.2,...,0.6}, bar width=0.8, axis
lines=left, width=8cm, height=8cm, enlarge x limits=0.1, enlarge y
limits=0.1, ]
\addplot+[ybar interval,mark=no] plot coordinates {(-0.5, 0.5) (0.5, 0.25) (1.5, 0.125)
(2.5, 0.0625) (3.5, 0.03125) (4.5, 0.015625) (5.5, 0.0078125) (6.5, 0.00390625) (7.5,
0.001953125)};
\end{axis}
\end{tikzpicture}
\end{document}
有没有办法将 y 轴向下移动,使条形图从水平轴发出?我还想将 y 轴稍微向右移动,使其与第一个矩形的左侧重合。
答案1
像这样?
您需要进行 enlarge y limits
相应设置:
\documentclass[oneside,english]{amsart}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[width=8cm, height=8cm,
axis lines=left,
ybar,
bar width=1,
xlabel={$k$}, ylabel={$\mathbb{P}(Z_2=k)$},
xtick={0,...,8},
enlarge x limits=0.1,
enlarge y limits={0.1, upper} % <----
]
\addplot +[ybar interval]
plot coordinates { (-0.5,0.5) (0.5,0.25) (1.5,0.125)
(2.5,0.0625) (3.5,0.03125) (4.5,0.015625)
(5.5,0.0078125) (6.5,0.00390625) (7.5,0.001953125)};
\end{axis}
\end{tikzpicture}
\end{document}
附录:
您可以在表中收集图表的数据,其中还定义了xtick
s。通过此更改,图表代码会更简单、更简短:
\documentclass[oneside,english]{amsart}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[width=8cm, height=8cm,
axis lines=left,
ybar,
bar width=1,
xlabel={$k$}, ylabel={$\mathbb{P}(Z_2=k)$},
ticklabel style = {font=\footnotesize},
xtick=data,
enlarge x limits=0.1,
ymax=0.55
]
\addplot table[y index=1] {1 0.5
2 0.25
3 0.125
4 0.0625
5 0.03125
6 0.015625
7 0.0078125
8 0.00390625
9 0.001953125
};
\end{axis}
\end{tikzpicture}
\end{document}
图表与之前相同。