我用 ShareLaTex 中的 pgfplot 制作了这两个图表,我的导师希望我将它们显示在一张图表中,这两个图分别用实线和虚线识别。图例还将定义哪个图代表 p=0,哪个图代表 p=1。
\documentclass{article}
\usepackage[margin=0.5in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{textcomp}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.9}
%\usepgfplotslibrary{external}
%\tikzexternalize
\begin{document}
\begin{figure}
Case I : $p=0$ and $n=0$
\begin{tikzpicture}
\begin{axis}[
title={ Energy density $\rho$},
xlabel={r/R},
ylabel={$\frac{\kappa}{C} \rho$},
xmin=0, xmax=1.2,
ymin=0, ymax=10,
xtick={0,0.2,0.4,0.6,0.8,1,1.2},
ytick={0,1,2,3,4,5,6,7,8,9,10}]
\addplot[
color=blue]
coordinates {
(0,8.71)(0.1,8.61)(0.2,8.33)(0.3,7.90)(0.4,7.35)(0.5,6.73)(0.6,6.08)(0.7,5.42)(0.8,4.78)(0.9,4.18)(1,3.61)
};
\end{axis}
\end{tikzpicture}
\caption{Hello world}\label{fig:myplot}
\end{figure}
Case II : $ p=1$ and $n=0$
\begin{tikzpicture}
\begin{axis}[
title={ Energy density $\rho$},
xlabel={r/R},
ylabel={$\frac{\kappa}{C} \rho$},
xmin=0, xmax=1.2,
ymin=0, ymax=10,
xtick={0,0.2,0.4,0.6,0.8,1,1.2},
ytick={0,1,2,3,4,5,6,7,8,9,10}]
\addplot[
color=blue]
coordinates {
(0,9.3725549039
)(0.1,9.3285550312
)(0.2,9.1985115839
)(0.3,8.9879707942
)(0.4,8.7051855159
)(0.5,8.3598886397
)(0.6,7.9619965855
)(0.7,7.5204841058
)(0.8,7.0425813594
)(0.9,6.5333394278
)(1,5.9955267351
)};
\\
\end{axis}
\end{tikzpicture}
\end{document}
答案1
只需删除代码的“中心”部分,即停止一个轴并启动第二个轴的部分。然后,您可以使用命令轻松添加图例\legend
。
在轴选项中,您将找到一些用于自定义图例的键。
输出
代码
\documentclass{article}
\usepackage[margin=0.5in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{textcomp}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.9}
%\usepgfplotslibrary{external}
%\tikzexternalize
\begin{document}
\begin{figure}[h]
\centering
\begin{tikzpicture}
\begin{axis}[
title={ Energy density $\rho$},
xlabel={r/R},
ylabel={$\frac{\kappa}{C} \rho$},
xmin=0, xmax=1.2,
ymin=0, ymax=10,
xtick={0,0.2,0.4,0.6,0.8,1,1.2},
ytick={0,1,2,3,4,5,6,7,8,9,10},
legend style={
cells={anchor=west},
draw=none, fill=none,
font=\scriptsize,
legend pos= south west,
}]
\addplot[
color=blue]
coordinates {
(0,8.71)(0.1,8.61)(0.2,8.33)(0.3,7.90)(0.4,7.35)(0.5,6.73)(0.6,6.08)(0.7,5.42)(0.8,4.78)(0.9,4.18)(1,3.61)
};
\addplot[
color=blue, dashed]
coordinates {
(0,9.3725549039
)(0.1,9.3285550312
)(0.2,9.1985115839
)(0.3,8.9879707942
)(0.4,8.7051855159
)(0.5,8.3598886397
)(0.6,7.9619965855
)(0.7,7.5204841058
)(0.8,7.0425813594
)(0.9,6.5333394278
)(1,5.9955267351
)};
\legend{Case I: $p=0$ and $n=0$, Case II: $p=1$ and $n=0$}
\end{axis}
\end{tikzpicture}
\caption{My combined plot}\label{fig:combined}
\end{figure}
\end{document}