我正在使用 pgfplots 堆叠条形图来显示家庭的能源总需求及其相关价格。当能源需求超过某个阈值时,就必须支付更高的价格。这通过条形图的红色和蓝色来表示。阈值由粗红色水平线显示。
我的问题是,我希望这条红线超出条形的宽度,这样它的宽度大约是条形宽度的 120%。 有没有可能实现这一点? 谢谢
\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ymin=0,ymax=4,
samples=3,
enlarge x limits={abs=0.5},
bar width=0.6,
ybar stacked,
legend pos=south east,
every axis/.append style={font=\footnotesize},
]
\draw[red, very thick] (axis cs:0.7,2) -- (axis cs:1.3,2);
\draw[red, very thick] (axis cs:1.7,2.5) -- (axis cs:2.3,2.5);
\draw[red, very thick] (axis cs:2.7,2.5) -- (axis cs:3.3,2.5);
\addplot
coordinates
{(1,1) (2,2.5) (3,1.5)};
\addplot
coordinates
{(1,0) (2,1) (3,0)};
\legend{low price, high price}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
您可以计算多余的宽度,并调整绘制线条两侧的坐标,10%
以使线条更宽20%
:
代码:
\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\newcommand{\MyBarWidth}{0.6}%
\pgfmathsetmacro{\ExcessBarWitdh}{0.1*\MyBarWidth}%
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ymin=0,ymax=4,
samples=3,
enlarge x limits={abs=0.5},
bar width=\MyBarWidth,
ybar stacked,
legend pos=south east,
every axis/.append style={font=\footnotesize},
]
\draw[red, very thick] (axis cs:0.7-\ExcessBarWitdh,2) -- (axis cs:1.3+\ExcessBarWitdh,2);
\draw[red, very thick] (axis cs:1.7-\ExcessBarWitdh,2.5) -- (axis cs:2.3+\ExcessBarWitdh,2.5);
\draw[red, very thick] (axis cs:2.7-\ExcessBarWitdh,2.5) -- (axis cs:3.3+\ExcessBarWitdh,2.5);
\addplot
coordinates
{(1,1) (2,2.5) (3,1.5)};
\addplot
coordinates
{(1,0) (2,1) (3,0)};
\legend{low price, high price}
\end{axis}
\end{tikzpicture}
\end{document}