在 Pgfplots latex 中绘制图形

在 Pgfplots latex 中绘制图形

我在乳胶中的 Pgfplots 中有一个图表,想添加四个三角形,它们的顶点位于 {(0,2) (4,0) 和蓝线上的给定点} {(0,2) (4,0) 和红线上的给定点} 并且三角形可以是不同的颜色并且有点透明吗?

代码:

\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = $x$,
    ylabel = {$f(x)$},
]
%Below the red parabola is defined
\addplot [
    domain=-10:10, 
    samples=100, 
    color=red,
]
{-4-x/2};
\addlegendentry{$-4-x/2$}
%Here the blue parabloa is defined
\addplot [
    domain=-10:10, 
    samples=100, 
    color=blue,
    ]
    {8-x/2};
\addlegendentry{$8-x/2$}

\end{axis}
\end{tikzpicture}

答案1

有几种可能的方法,其中一种如下所示。

注意坐标中的使用axis cs。其目的是声明坐标应解释为axis坐标,否则不予假定。除非如果您有\pgfplotsset{compat=1.11}(或更新版本),则假定轴坐标,因此axis cs:不需要前缀。

在此处输入图片描述

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[
  declare function={ % not really necessary, just for convenience
    f(\x) = -4 - \x/2;
    g(\x) = 8 - \x/2;
    }
    ]
\begin{axis}[
    axis lines = left,
    xlabel = $x$,
    ylabel = {$f(x)$},
]
%Below the red parabola is defined
\addplot [
    domain=-10:10, 
    samples=2, % it's a straight line, 2 points are enough
    color=red,
]
{f(x)};
\addlegendentry{$-4-x/2$}
%Here the blue parabola is defined
\addplot [
    domain=-10:10, 
    samples=2, 
    color=blue,
    ]
    {g(x)};
\addlegendentry{$8-x/2$}

% define named coordinates 
\coordinate (a) at (axis cs:0,2);
\coordinate (b) at (axis cs:4,0);

% create filled triangles
\fill [red,opacity=0.5] (a) -- (b) -- (axis cs:0,{f(0)}) -- cycle;
\fill [blue,opacity=0.5] (a) -- (b) -- (axis cs:0,{g(0)}) -- cycle;

\end{axis}
\end{tikzpicture}
\end{document}

相关内容