【漫漫科研路\pgfplots】克服繪製色溫圖時,數據量大出現的內存限制

在科研論文寫作中,經常會遇到畫色溫圖,3D圖。此時一般輸入的數據量比較大,導致在Latex中使用Tikz畫圖時出現內存不足的情況。常常報錯如下:

! TeX capacity exceeded, sorry [main memory size=5000000].

參考pgfplots手冊中的第六章,我們有以下解決方案:

  • 使用LuaTex進行編譯
    有些版本不含LuaTex
  • 對輸入數據採樣降低數據量
    不是從本質上解決問題,降低了精度
  • 使用其它軟件畫圖,e.g., MATLAB
  • 增大LaTex的編譯內存

本文主要介紹如何在MacOS系統中Texlive平臺下,克服內LaTex內存限制。關於在Linux和MiKTEX環境下,pgfplots手冊已給了說明,這裏不再贅述。

解決辦法:在Texlive安裝目錄中找到texmf.cnf文件並編輯:

其安裝目錄在

/usr/local/texlive/2018/texmf-dist/web2c/texmf.cnf

注意:/usr/local/texlive/2018/texmf.cnf也有相同的文件,編輯這個文件無法解決問題

其內容修改如下:
在這裏插入圖片描述
注意:修改的內存大小不能超過實際內存大小,我的是8G.

最後,打開終端進入安裝目錄下,執行

sudo texhash 

若發生文件不可寫的情況,可以使用chmod 777 來更改文件讀寫權限。


下面,我們通過實例來驗證:

  • 數據產生
    我們使用Matlab的peaks函數來產生peaks.dat文件用於tikz畫圖的輸入數據。其代碼如下:

    clear all
    clc
    close all
    
    lambda_total=2;% the sum of Z
    [X,Y,Z] = peaks(100);
    Z(Z<0)=0;
    Z=Z/sum(sum(Z))*lambda_total;
    
    x_temp=repmat(1:100,100,1);% X-axis
    x_temp=x_temp(:);  
    y_temp=repmat(1:100,1,100);%Y-axis
    
    xyz=['x y z'];
    dlmwrite('peaks.dat',xyz,'delimiter',' ');
    for x_ind=1:size(Z,1)
        for y_ind=1:size(Z,2)
            % for one point (x,y,z), we use 4 coordinates (x,y,z) (x,y+1,z) (x+1,y+1,z) (x+1,y,z) to form a patch
            xyz=[x_ind y_ind Z(x_ind, y_ind);x_ind y_ind+1 Z(x_ind, y_ind);x_ind+1 y_ind+1 Z(x_ind, y_ind);x_ind+1 y_ind Z(x_ind, y_ind)];
            if(x_ind==1&&y_ind==1)
                dlmwrite('peaks.dat',xyz,'delimiter',' ','-append','roffset',0);
            else
                dlmwrite('peaks.dat',xyz,'delimiter',' ','-append','roffset',1);
            end
        end
    end
    
  • 在Tikz中畫圖
    本文使用了patch來畫圖,也可以改用surf, mesh等。完整latex源代碼如下:

     \documentclass{standalone}
    \def\pgfsysdriver{pgfsys-dvipdfmx.def}
    \usepackage{tikz}
    \usepackage{pgfplots}
    \pgfplotsset{width=7cm,compat=1.14}
    
    \begin{document}
    \begin{tikzpicture} 
    	\begin{axis}[
    		colorbar,
            xmin=1,xmax=101,
    		ymin=1,ymax=101,
    		xlabel={X-axis (m)},
    		ylabel={Y-axis (m)},
    	]
    	\addplot [patch,patch type=rectangle] 
    		table [point meta=\thisrow{z}]
    		{peaks.dat }; 
        \end{axis}
    \end{tikzpicture}
    \end{document}
    

    畫圖效果如下:
    在這裏插入圖片描述

發佈了171 篇原創文章 · 獲贊 129 · 訪問量 68萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章