我正在尝试制作这种线谱。我找到了这种类型的代码,但波浪符号在我的乳胶环境中无法识别。我有最新版本的乳胶
\tikzset{
% define the bar graph element
bar/.pic={
\fill (-.1,0) rectangle (.1,#1) (0,#1) node[above,scale=1/2]{$#1$};
}
}
\begin{document}
\begin{tikzpicture}[y=4cm]
\draw
% the main axis
(-3,0) edge[-latex] (3,0)
% draw the distribution and label it
foreach[count=\i from -2] ~ in {1/16,4/16,6/16,4/16,1/16}{
(\i,0) pic[red]{bar=~} node[below]{$\i$}
};
\end{tikzpicture}
答案1
所提出的代码不可执行且不完整。我做了一些更改以获得如下可见结果(您可以删除网格和左侧比例):
代码:
\documentclass[10pt,a4paper]{article}
\usepackage{tikz}
\tikzset{
% define the bar graph element
bar/.pic={
\fill (-.1,0) rectangle (.1,#1) (0,#1) node[above]{\bfseries $#1$};
}
}
\begin{document}
\begin{tikzpicture}[y=10cm,scale=2]
\draw[gray!20] (-3,-.1) grid (3,.3);
\foreach \i in {-0.1,0.0,0.1,0.2,0.3} \draw (-3.1,\i) node[left] () {$\i$};
\draw
% the main axis
(-3,0) edge[-latex] (3,0)
% draw the distribution and label it
foreach[count=\i from -2] ~ in {1/16,4/16,6/16,4/16,1/16}{
(\i,0) pic[red]{bar=~} node[below]{\Large $\i$}
};
\end{tikzpicture}
\end{document}
答案2
根据 MWE 中“yticks + bars”循环中给出的“bars”数据,您的图表不正确。它应该是这样的:
\pic
MWE,其中我使用 3mm 的简单线条宽度代替您的(因此代码比您的更简单、更清晰),是:
\documentclass[margin=3pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{tikzpicture}
\draw[gray!20] (-3,-1) grid (3,5);
% x-axis
\draw[-Straight Barb] (-3,0) -- (3,0);
% xticks
\foreach \i in {-0.1,0,0.1,0.2,0.3,0.4,0.5} \node[left] at (-3,10*\i) {$\i$};
% yticks + bars
\foreach \i [count=\j from -2] in {1/16,4/16,6/16,4/16,1/16}
\draw[red, line width=3mm] (\j,0) node[below, text=black] {$\j$} -- ++ (0,10*\i)
node[very thin, above, font=\scriptsize, inner sep=1pt] {$\i$};
\end{tikzpicture}
\end{document}