请考虑以下 MWE:
\documentclass[11pt,twoside]{article}
\usepackage[spanish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usetikzlibrary{arrows.meta, patterns}
\pgfplotsset{compat=1.8}
\usepackage{amsmath}
\pgfplotsset{
Cus/.style={
axis equal image,
axis lines = center,
xlabel = $x$,
ylabel = $y$
}
}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{ticks=none}
\begin{axis}[
Cus,
xmin=-2.1, xmax=4.1,
legend pos=outer north east,
legend cell align={left}
]
\addplot[very thick,blue,samples=300,domain=1:4.1] {sqrt((x-1)/2)};
\addplot[very thick,blue,samples=300,domain=1:4.1] {-sqrt((x-1)/2)};
\addlegendentry{$x-2y^2=1$}
\addplot[very thick,red,samples=300,domain=1:4.1] {sqrt(x-1)};
\addplot[very thick,red,samples=300,domain=1:4.1] {-sqrt(x-1)};
\addlegendentry{$x-y^2=1$}
\end{axis}
\end{tikzpicture}
\end{document}
我做错了什么?如何让第二个图例具有相应的颜色(红色)?
谢谢!
答案1
发生这种情况的原因是,您添加了四个图,但只添加了两个图例条目。这些条目对应于前两个图,它们都是蓝色的。尝试添加另一个图例条目;它将是红色的。
解决这个问题的简单方法是用 画出上部部分\addlegendentry
,然后用 画出下部部分\addlegendentry
。
\documentclass[11pt,twoside]{article}
\usepackage[spanish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usetikzlibrary{arrows.meta, patterns}
\pgfplotsset{compat=1.8}
\usepackage{amsmath}
\pgfplotsset{
Cus/.style={
axis equal image,
axis lines = center,
xlabel = $x$,
ylabel = $y$
}
}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{ticks=none}
\begin{axis}[
Cus,
xmin=-2.1, xmax=4.1,
legend pos=outer north east,
legend cell align={left}
]
\addplot[very thick,blue,samples=300,domain=1:4.1] {-sqrt((x-1)/2)};
\addlegendentry{$x-2y^2=1$}
\addplot[very thick,red,samples=300,domain=1:4.1] {-sqrt(x-1)};
\addlegendentry{$x-y^2=1$}
\addplot[very thick,blue,samples=300,domain=1:4.1] {sqrt((x-1)/2)};
\addplot[very thick,red,samples=300,domain=1:4.1] {sqrt(x-1)};
\end{axis}
\end{tikzpicture}
\end{document}
答案2
为了避免添加“虚拟”图例条目,您可以使用forget plot
或 - 在给定的示例中 - 一次性以参数方式绘制图。
有关详细信息,请查看代码中的注释。
% used PGFPlots v1.15
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{
Cus/.style={
axis equal image,
axis lines=center,
xlabel=$x$,
ylabel=$y$,
},
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
Cus,
xmin=-2.1,
xmax=4.1,
legend pos=outer north east,
legend cell align={left},
ticks=none,
% moved common `\addplot' options here
no markers,
smooth,
domain=1:4.1,
samples=101,
every axis plot/.append style={
very thick,
},
]
% either add `forget plot' to each first plot half, which avoids
% increasing the `cycle list' and avoids counting for the legend ...
\addplot+ [forget plot] {sqrt((x-1)/2)};
\addplot {-sqrt((x-1)/2)};
\addlegendentry{$x-2y^2=1$}
% \addplot+ [forget plot] {sqrt(x-1)};
% \addplot {-sqrt(x-1)};
% ... or draw the lines as parametric plots which doesn't need that
% much `samples' and can be drawn in one go
\addplot+ [domain=-2:2,samples=25] (x^2 + 1,x);
\addlegendentry{$x-y^2=1$}
\end{axis}
\end{tikzpicture}
\end{document}