[Tex/LaTex] Rescaling gnuplottex to fit in subfigure

gnuplotscalingsubcaption

I would like to use gnuplot environments (from the gnuplottex package) in subfigures (from the subcaption package).

How can I change the size of the gnuplot graph, so that it will fit into the subfigure and doesn't overlay with the graph next to it?

This is the code I used:

\documentclass{scrbook}
\usepackage[utf8]{inputenx}
\usepackage[T1]{fontenc}

\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage{subcaption}
\usepackage[miktex]{gnuplottex}

\begin{document}
\begin{figure}[htbp]
 \begin{subfigure}[b]{.5\textwidth}
  \begin{gnuplot}[terminal=cairolatex]
   plot sin(x)
  \end{gnuplot}
  \caption{A subfigure}
 \end{subfigure}%
 \begin{subfigure}[b]{.5\textwidth}
  \begin{gnuplot}[terminal=cairolatex]
   plot sin(x)
  \end{gnuplot}
  \caption{Another subfigure}
 \end{subfigure}
 \caption{A figure}
\end{figure}
\end{document}

And this is its result:

two subfigures, one overlays the other

EDIT:
John commented this solution: Replace \begin{gnuplot}[terminal=cairolatex] by \begin{gnuplot}[terminal=cairolatex, terminaloptions={size 7cm, 4cm}].
Now I have follow-up questions:
Is it possible to specify the size as 0.4\textwidth instead of 7cm?
Could I just specify the width but not the height and keep the aspect ratio?

Best Answer

I found a post on another question that answered my question: How do I change the aspect ratio of gnuplot output?

This is how I solved my problem:

\documentclass{scrbook}
\usepackage[utf8]{inputenx}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage{subcaption}
\usepackage{gnuplottex}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\convertlen}{ O{cm} m }
 {
  \dim_to_unit:nn { #2 } { 1 #1 } cm
 }
\ExplSyntaxOff


\begin{document}

\begin{figure}[htbp]
 \centering
 \begin{subfigure}[b]{.45\textwidth}
  \begin{gnuplot}[terminal = cairolatex, terminaloptions = {size \convertlen{\textwidth},\convertlen{.3\textheight}}]
   plot sin(x)
  \end{gnuplot}
  \caption{A subfigure}
  \label{fig:1a}
 \end{subfigure}%
 \hfill
 \begin{subfigure}[b]{.45\textwidth}
  \begin{gnuplot}[terminal = cairolatex, terminaloptions = {size \convertlen{\textwidth},\convertlen{.3\textheight}}]
   plot sin(x)
  \end{gnuplot}
  \caption{Another subfigure}
  \label{fig:1b}
 \end{subfigure}
 \caption{A figure}\label{fig:1}
\end{figure}

\end{document}