Pgfplots:ybar 无间隙且数据中间对齐

Pgfplots:ybar 无间隙且数据中间对齐

我想表示函数的近似值。我使用ybar具有特定样本大小的近似值。但是,使用标准时,ybar我会在单个条形之间产生我不想要的间隙。另一方面,如果我使用ybar interval建议的在此主题中条形图向右移动。

如何才能获得零间隙和条形中间对齐的组合,如下例所示:在此处输入图片描述

我当前的代码:

\documentclass{standalone}

\usepackage{pgfplots}

\pgfplotsset{compat=1.14}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
  xmin=-1,
  xmax=7,
  ymin=0,
  ymax=3.5,
  enlargelimits=true,
  axis lines=middle,
  clip=false,
  domain=0:2*pi,
  axis on top
]
%\addplot [draw=gray, fill=gray!10, ybar interval, samples=11]{sin(deg(x))+2}\closedcycle;
%\addplot [draw=gray, fill=gray!10, ybar, bar width=1, samples=11]{sin(deg(x))+2}\closedcycle;
\addplot [draw=gray, fill=gray!10, ybar=0pt, samples=11]{sin(deg(x))+2}\closedcycle;
\addplot[smooth, thick,domain=0:2*pi]{sin(deg(x))+2};
\end{axis}
\end{tikzpicture}
\end{document}

答案1

您可以将设置bar width为等于样本之间的距离。如果范围为 ,0:2pi则设置 11 个样本,bar width=2*pi/10以获得以下结果:

在此处输入图片描述

\documentclass{standalone}

\usepackage{pgfplots}

\pgfplotsset{compat=1.14}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
  xmin=-1,
  xmax=7,
  ymin=0,
  ymax=3.5,
  axis lines=middle,
  clip=false,
  domain=0:2*pi,
  axis on top,
  bar width=2*pi/10
]
%\addplot [draw=gray, fill=gray!10, ybar interval, samples=11]{sin(deg(x))+2}\closedcycle;
%\addplot [draw=gray, fill=gray!10, ybar, bar width=1, samples=11]{sin(deg(x))+2}\closedcycle;
\addplot [draw=gray, fill=gray!10, ybar=0pt, samples=11]{sin(deg(x))+2}\closedcycle;
\addplot[smooth, thick,domain=0:2*pi]{sin(deg(x))+2};
\end{axis}
\end{tikzpicture}
\end{document}

相关内容