跟小D每日学口语

tikz作图

如果你选择了Latex,那也就意味着义无反顾的勇气。作图是科技写作的重要部分,工科生最熟悉的作图软件通常是matlab,它的缺点是难以与Latex无缝融合,比如字体的统一就是个大问题。好在有能人意识到这个问题,并且做出了出色的转化工具——matlab2tikz,可以将matlab的图转化为tex文件,然后在主文档中直接\input即可。接下来的问题是:

1)如果图很多,主文档编译很变得很慢;

2)能否将每一幅matlab的图通过matlab2tikz转化成一幅pdf格式的图?这样就可以在主文档以图的形式包含即可。

没有做不到,只有想不到的。tikz/pgf(pgfplots)可以实现这一功能。到目前为止,还没发现有效的xeLatex编译方法,pgfplots手册都是以pdflatex编译的。以下是一个完成的例子:

\documentclass[UTF8]{article}%UTF8必须大写

\usepackage{CTEX}%大写

\usepackage{tikz,pgfplots}

\usepgfplotslibrary{external}

\tikzexternalize% activate externalization!

\begin{document}

 

         \begin{figure}

                  \centering

                  \begin{tikzpicture}

                  \begin{axis}[

                  width=8cm,

                  height=4cm,

                  xlabel={时间坐标},

                  ylabel={幅度坐标},title={示例1}]

                  \addplot {x^2};

                  \end{axis}

                  \end{tikzpicture}

                  \caption{第一幅外部图例子}%输出的图像文件不包含caption

         \end{figure}

         \begin{figure}

                  \centering

                  \begin{tikzpicture}

                  \begin{axis}[

                  width=8cm,

                  height=4cm,

                  xlabel={时间坐标},

                  ylabel={幅度坐标},title={示例2}]

                  \addplot {x^3};

                  \end{axis}

                  \end{tikzpicture}

                  \caption{第二幅图}

         \end{figure}

\end{document}

且将命令行改为pdflatex -synctex=1 -interaction=nonstopmode --shell-escape %.tex。编译之后,除了可以生成主文档对应的pdf文件,还会生成每幅图对应的pdf文件,自动去除白边哦。

  pdfLatex的内存分配不如luaLatex灵活,因此,当图像数据量较大时,建议选用luaLatex编译方法。一个完整的例子(Logistic分岔图):

\ifx\directlua\@undefined
\else
\RequirePackage{luatex85}
\RequirePackage{shellesc}
\fi

\documentclass[tikz]{article}
\usepackage{luatexja-fontspec}
\setmainjfont{FandolSong}
\usepackage{luacode}
\usepackage{filecontents}
\usepackage{pgfplots}
\usepgfplotslibrary{external}
\tikzexternalize

\begin{luacode*}
  function logistic()

    local function map(r,x)
      return r*x*(1-x)
    end

    for r = 2.5,4,0.005 do
      x = 0.1
      for i = 1, 200 do
        x = map(r,x)
      end
      for i = 1, 200 do
        x = map(r,x)
        tex.sprint("("..r..","..x..")")
      end
    end
  end
\end{luacode*}

\begin{document}
\begin{figure}
\begin{tikzpicture}
  \begin{axis}[xlabel={参数$\mu$},ylabel={幅度}]
  \edef\logisticplot{\noexpand\addplot [color=black!10, mesh, only marks,
  mark size = 0.05pt, opacity = 0.1] coordinates{ \directlua{logistic()} };}
  \logisticplot
  \end{axis}
\end{tikzpicture}
\end{figure}
\end{document}

命令行设置:lualatex.exe -synctex=1 -interaction=nonstopmode -shell-escape %.tex。

luaLatex另一亮点是支持编程语言。

posted on 2017-02-20 18:36  湘厦人  阅读(910)  评论(0编辑  收藏  举报

导航