尝试在基本 PGF 中制作棒棒糖图(又名梳状图),但如何绘制垂直线使其在图的 y=0 处结束?

尝试在基本 PGF 中制作棒棒糖图(又名梳状图),但如何绘制垂直线使其在图的 y=0 处结束?

我想为棒棒糖图(又称梳状图)创建一个新的 TikZ 可视化工具。我知道我可以使用 pgfplots,但我正在尝试了解 TikZ/PGF 的内部原理。我改编了手册中的示例(第 83.4 节),并得出了这个(在我看来,虽然很小,但仍然相当大)工作示例:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{datavisualization}
\usetikzlibrary{datavisualization.formats.functions}

\pgfooclass{lollipop visualizer}
{
  % Stores the name of the visualizer. This is needed for filtering
  % and configuration
  \attribute name;
  
  % The constructor. Just setup the attribute.
  \method lollipop visualizer(#1) { \pgfooset{name}{#1} }
  
  % Connect to visualize signal.
  \method default connects() {
    \pgfoothis.get handle(\me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\me,visualize,visualize datapoint signal)
  }

  % This method is invoked for each data point. It checks whether the
  % data point belongs to the correct visualizer and, if so, calls the
  % macro \dovisualization to do the actual visualization.
  \method visualize() {
    \pgfdvfilterpassedtrue
    \pgfdvnamedvisualizerfilter
    \ifpgfdvfilterpassed
      \dovisualization
    \fi
  }
}

\newdimen\lastx

\def\dovisualization{
  \pgfkeysvalueof{/data point/\pgfoovalueof{name}/execute at begin}
  \pgfpathcircle{\pgfpointdvdatapoint}{1pt}
  \pgfextractx{\lastx}{\pgfpointdvdatapoint}
  \pgfpathlineto{\pgfpoint{\lastx}{0cm}}
  % \pgfusepath is done by |execute at end|
  \pgfkeysvalueof{/data point/\pgfoovalueof{name}/execute at end}
}

\tikzdatavisualizationset{
  visualize as lollipop/.style={
    new object={
      when=after survey,
      store=/tikz/data visualization/visualizers/#1,
      class=lollipop visualizer,
      arg1=#1
    },
    new visualizer={#1}{%
      color=visualizer color,
      % a color setup by the style sheet
      every path/.style={fill,draw}, % fill and draw the circle by default,
    }{}, % let's ignore legends in this example
    /data point/set=#1
  },
}

\begin{document}

\begin{tikzpicture}
\datavisualization [
  scientific axes,
  visualize as lollipop/.list={a},
  style sheet=strong colors]
data [set=a, format=function] {
  var x : interval [-7:7] samples 29;
  func y = sin(\value x r);
};
\end{tikzpicture}

\end{document}

运行此示例可得到:

由于垂直茎太长,导致棒棒糖(或梳子)图不正确

这显然是错误的,因为棒棒糖茎应该只到图的 y=0,但它们却到图像的下边缘(图像的 y=0)。原因很明显:宏\dovisualization

  \pgfpathlineto{\pgfpoint{\lastx}{0cm}}

因此这条线将延伸到图片y=0。但是我如何获得正确的图像 y 值,其中阴谋y=0 吗?

相关内容