答案1
这是一个例子。代码包含几条注释,但如果有任何不清楚的地方,请询问。
\documentclass[border=5mm]{standalone}
\usepackage{pgfplotstable} % also loads pgfplots
% make a table containing y-values and labels for (some of) the data points
\pgfplotstableread[col sep=comma]{
y,label
8,$Y_{1}$
2,
5.6,$Y_{2}$
5,$Y_{3}$
6,
4,
9,$Y_{j}$
10,
4,
}\mydata
\begin{document}
\begin{tikzpicture}
\begin{axis}[
%
axis lines=middle,
% labels for axes
ylabel={$X_i$},
xlabel={$i$},
% set axes limits
ymin=0,
xmin=0,
xmax=9.9,
% define where to place ticks on the axes
% and what text labels to use for the ticks
ytick={4.5},
yticklabels={$u$},
xtick={1,2,3,9},
xticklabels={$1$,$2$,$3$,$n$},
tickwidth=0pt,
% turn on grid lines for ticks on the y-axis
ymajorgrids,
% set the style of the single grid line
grid style={densely dotted, gray}
]
\addplot [
% comb plots are lines from the axis to the point
ycomb,
thick,
% nodes near coords is for adding automatic labels at data points
nodes near coords,
% set the style of those nodes
nodes near coords style={font=\small},
% the following states that the text used for the labels should
% be given explicitly in the data stream
% symbolic means that it should not be parsed as a number
point meta=explicit symbolic
]
table[
% define the x-coordinate
x expr=\coordindex+1,
% get y-values from the column named y in the table
y=y,
% get the data for the point labels from the column named label
meta=label
] {\mydata};
\addplot [
ycomb,
thick,
gray
]
table[
x expr=\coordindex+1,
% the y-coordinate is defined by the given calculation, i.e.
% the smallest value of the y-value from the table and 4.5
y expr={min(\thisrow{y}, 4.5)}
] {\mydata};
\end{axis}
\end{tikzpicture}
\end{document}