1. 程式人生 > >在LaTeX中使用強大的pgfplots繪圖包

在LaTeX中使用強大的pgfplots繪圖包

The pgfplots package is a powerful tool, based on tikz, dedicated to create scientific graphs.

Introduction

Pgfplots is a visualization tool to make simpler the inclusion of plots in your documents. The basic idea is that you provide the input data/formula and pgfplots does the rest.

pgfplots example
\begin
{tikzpicture} \begin{axis} \addplot[color=red]{exp(x)}; \end{axis} \end{tikzpicture} %Here ends the furst plot \hskip 5pt %Here begins the 3d plot \begin{tikzpicture} \begin{axis} \addplot3[ surf, ] {exp(-x^2-y^2)*x}; \end{axis} \end{tikzpicture}
  Output

Pgfplots3.png

Since pgfplot

 is based on tikz the plot must be inside a tikzpicture environment. Then the environment declaration \begin{axis},\end{axis} will set the right scaling for the plot, check the Reference guide for other axis environments.

To add an actual plot, the command \addplot[color=red]{log(x)}; is used. Inside the squared brackets some options can be passed, in this case we set the colour of the plot to red

; the squared brackets are mandatory, if no options are passed leave a blank space between them. Inside the curly brackets you put the function to plot. Is important to remember that this command must end with asemicolon ;.

To put a second plot next to the first one declare a new tikzpicture environment. Do not insert a new line, but a small blank gap, in this case hskip 10pt will insert a 10pt-wide blank space.

The rest of the syntax is the same, except for the \addplot3 [surf,]{exp(-x^2-y^2)*x};. This will add a 3dplot, and the optionsurf inside squared brackets declares that it's a surface plot. The function to plot must be placed inside curly brackets. Again, don't forget to put a semicolon ; at the end of the command.

Note: It's recommended as a good practice to indent the code - see the second plot in the example above - and to add a comma , at the end of each option passed to \addplot. This way the code is more readable and is easier to add further options if needed.

The document preamble

To include pgfplots in your document is very easy, add the next line to your preamble and that's it:

\usepackage{pgfplots}

Some additional tweaking for this package can be made in the preamble. To change the size of each plot and also guarantee compatibility backwards (recommended) add the next line:

\pgfplotsset{width=10cm,compat=1.9}

This changes the size of each pgfplot figure to 10 cementers, which is huge; you may use different units (pt, mm, in). The compatparameter is for the code to work on the package version 1.9 or latter.

Since LaTeX was not initially conceived with plotting capabilities in mind, when there are several pgfplot figures in your document or they are very complex, it takes a considerable amount of time to render them. To improve the compiling time you can configure the package to export the figures to separate PDF files and then import them into the document, just add the code shown below to the preamble:

\usepgfplotslibrary{external}

\tikzexternalize

By now this functionality is not implemented in ShareLaTeX, but you can try it in your local LaTeX installation.

2D plots

Pgfplots 2D plotting functionalities are vast, you can personalize your plots to look exactly what you want. Nevertheless, the default options usually give very good result, so all you have to do is feed the data and LaTeX will do the rest:

Plotting mathematical expressions

To plot mathematical expressions is really easy:

mathematical expression
\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = $x$,
    ylabel = {$f(x)$},
]
%Below the red parabola is defined
\addplot [
    domain=-10:10, 
    samples=100, 
    color=red,
]
{x^2 - 2*x - 1};
\addlegendentry{$x^2 - 2x - 1$}
%Here the blue parabloa is defined
\addplot [
    domain=-10:10, 
    samples=100, 
    color=blue,
    ]
    {x^2 + 2*x + 1};
\addlegendentry{$x^2 + 2x + 1$}
 
\end{axis}
\end{tikzpicture}
  Output

Pgfplots4.png

Let's analyse the new commands line by line:

axis lines = left.
This will set the axis only on the left and bottom sides of the plot, instead of the default box. Further customisation options at thereference guide.
xlabel = $x$ and ylabel = {$f(x)$}.
Self-explanatory parameter names, these will let you put a label on the horizontal and vertical axis. Notice the ylabel value in between curly brackets, this brackets tell pgfplots how to group the text. The xlabel could have had brackets too. This is useful for complicated labels that may confuse pgfplot.
\addplot.
This will add a plot to the axis, general usage was described at the introduction. There are two new parameters in this example.
domain=-10:10.
This establishes the range of values of x.
samples=100.
Determines the number of points in the interval defined by domain. The greater the value of samples the sharper the graph you get, but it will take longer to render.
\addlegendentry{$x^2 - 2x - 1$}.
This adds the legend to identify the function x^2 - 2x - 1.

To add another graph to the plot just write a new \addplot entry.

Plotting from data

Scientific research often yields data that has to be analysed. The next example shows how to plot data with pgfplots:

plotting from data
\begin{tikzpicture}
\begin{axis}[
    title={Temperature dependence of CuSO$_4\cdot$5H$_2$O solubility},
    xlabel={Temperature [\textcelsius]},
    ylabel={Solubility [g per 100 g water]},
    xmin=0, xmax=100,
    ymin=0, ymax=120,
    xtick={0,20,40,60,80,100},
    ytick={0,20,40,60,80,100,120},
    legend pos=north west,
    ymajorgrids=true,
    grid style=dashed,
]
 
\addplot[
    color=blue,
    mark=square,
    ]
    coordinates {
    (0,23.1)(10,27.5)(20,32)(30,37.8)(40,44.6)(60,61.8)(80,83.8)(100,114)
    };
    \legend{CuSO$_4\cdot$5H$_2$O}
 
\end{axis}
\end{tikzpicture}
  Output

Pgfplots2.png


There are some new commands and parameters here:

title={Temperature dependence of CuSO$_4\cdot$5H$_2$O solubility}.
As you might expect, assigns a title to the figure. The title will be displayed above the plot.
xmin=0, xmax=100, ymin=0, ymax=120.
Minimum and maximum bounds of the x and y axes.
xtick={0,20,40,60,80,100}, ytick={0,20,40,60,80,100,120}.
Points where the marks are placed. If empty the ticks are set automatically.
legend pos=north west.
Position of the legend box. Check the reference guide for more options.
ymajorgrids=true.
This Enables/disables grid lines at the tick positions on the y axis. Use xmajorgrids to enable grid lines on the x axis.
grid style=dashed.
Self-explanatory. To display dashed grid lines.
mark=square.
This draws a squared mark at each point in the cordinates array. Each mark will be connected with the next one by a straight line.
coordinates {(0,23.1)(10,27.5)(20,32)...}
Coordinates of the points to be plotted. This is the data you want analyse graphically.

If the data is in a file, which is the case most of the time; instead of the commands \addplot and coordinates you should use\addplot table {file_with_the_data.dat}, the rest of the options are valid in this environment.

Scatter plots

Scatter plots are used to represent information by using some kind of marks, these are common, for example, when computing statistical regression. Lets start with some data, the sample below is to show the structure of the data file we are going to plot (see the end of this section for a link to the LaTeX source and the data file):

GPA ma ve co un

3.45 643 589 3.76 3.52

2.78 558 512 2.87 2.91

2.52 583 503 2.54 2.4

3.67 685 602 3.83 3.47

3.24 592 538 3.29 3.47

2.1 562 486 2.64 2.37

The next example is a scatter plot of the first two columns in this table:

scatter plot
\begin{tikzpicture}
\begin{axis}[
    enlargelimits=false,
]
\addplot+[
    only marks,
    scatter,
    mark=halfcircle*,
    mark size=2.9pt]
table[meta=ma]
{scattered_example.dat};
\end{axis
            
           

相關推薦

LaTeX使用強大pgfplots繪圖

The pgfplots package is a powerful tool, based on tikz, dedicated to create scientific graphs. Introduction Pgfplots is a visualization too

LaTeX的TikZ巨集繪圖簡單示例

  LaTeX中的巨集包TikZ在繪圖方面的功能很強,我已將相關的說明文件傳送到51CTO中(http://down.51cto.com/data/2456407 ),大家可以去下載查閱,不需要下載豆。  下面舉一個非常簡單的例子,複雜的繪圖請大家自己看說明文件。這裡順便談一下LaTeX的學習,建議邊用邊學,

LaTeX的TikZ宏繪圖簡單示例

lac fff under 字體 etc left use 說明 per LaTeX中的宏包TikZ在繪圖方面的功能很強,我已將相關的說明文檔發送到51CTO中(http://down.51cto.com/data/2456407 ),大家可以去下載查閱,不需要下載豆。  

LaTeX使用tikz巨集及其擴充套件共同繪製UML圖

  LaTeX巨集包tikz的繪圖功能很強,完全可以繪製UML的各種圖形,並且在tikz的基礎上擴展出不少這方面的巨集包。前面我介紹過巨集包tikz-uml,這個巨集包功能不錯,只是外觀上略微有些不足。所以我現在還是立足於tikz的基礎功能,結合tikz-uml巨集包一起繪製UML圖。  下面直接給出示例程式

LaTeX使用tikz宏及其擴展共同繪制UML圖

fine 基礎 str vpd 比較 排列 off 並且 ima LaTeX宏包tikz的繪圖功能很強,完全可以繪制UML的各種圖形,並且在tikz的基礎上擴展出不少這方面的宏包。前面我介紹過宏包tikz-uml,這個宏包功能不錯,只是外觀上略微有些不足。所以我現在還是立足

LaTeX使用tikz巨集及其擴充套件共同繪製UML圖之備忘二

  本篇所舉例子檔案前面的內容與備忘一(在LaTeX中使用tikz巨集包及其擴充套件包共同繪製UML圖之備忘一)中的示例一是一樣的,這裡不再列出。 示例三 \begin{center} \begin{tikzpicture} \node(PaydayTransaction)[basic_

LaTeX使用tikz宏及其擴展共同繪制UML圖之備忘二

nor .com ssi RoCE alc node 分享 class -- 本篇所舉例子文件前面的內容與備忘一(在LaTeX中使用tikz宏包及其擴展包共同繪制UML圖之備忘一)中的示例一是一樣的,這裏不再列出。 示例三 % 51CTO 陸巍的博客 \begin{cent

利用TikZ 宏LaTeX 繪制流程圖

n! mon black gre www. too right lib 詳細 發現用TikZ畫流程圖其實挺方便的,對於簡單的圖應該比visio簡單。 使用的宏包: \usepackage{tikz,mathpazo} \usetikzlibrary{shapes.geom

LaTeX使用subfig引用子圖示號

[toc] 使用LaTeX的過程中總免不了要在一個大圖中包含好幾個子圖。當前在LaTeX中插入多個子圖使用的最新版本的包圍subfig,基本上好的主流的國外期刊都會具體要求使用該包。 1 問題描述 我在使用該包的過程中遇到的一個問題為: 我需要的子圖的展

Latex圖表位置的控制

sin nbsp txt latex fig otto page 其中 -o \begin{figure}[!htbp] 其中htbp是可選的,它們分別代表 !-忽略“美學”標準 h-here t-top b-bottom p-page-of-its-own

python強大的format函數

分別是 china 基本上 類型 logs __init__ span () cnblogs 自python2.6開始,新增了一種格式化字符串的函數str.format(),此函數可以快速處理各種字符串。語法 它通過{}和:來代替%。 請看下面的示例,基本上總結了forma

純AS3項目如何引用fl的類

設計 最好 libs ons pro rip 添加 ide 環境 fl包在Flash IDE中是獨立的類庫,在Flex中是無法直接引用的,那麽如果Flex想要使用Flash IDE中fl包該怎麽辦呢? 需要在Flash IDE安裝路徑下,找到下面的flash.swc文件添加

Python ,matplotlib繪圖無法顯示中文的問題

face blank pop false nbsp star view start 顯示中文 在python中,默認情況下是無法顯示中文的,如下代碼: [python] view plain copy import matplotlib.pyp

golangtcp socket粘問題和處理

enc pack 獲取 人工 過程 reader 主動 exit ase 轉自:http://www.01happy.com/golang-tcp-socket-adhere/ 在用golang開發人工客服系統的時候碰到了粘包問題,那麽什麽是粘包呢?例如我們和客戶端約定數據

Eclipse 將projectBuild Path引用的jar自己主動復制到WEB-INF下的lib目錄下

技術分享 異常 pat building -1 選擇 否則 sem rop 在用用 Eclipse進行Java Web開發時,web應用中引用的jar須要復制到WEB-INF下的lib目錄下,否則常常出現ClassNotFound異常。 通過以下方法,能夠不用手動拷貝jar

Lua強大的元方法__index詳解

代碼 tab 字段 pri 說過 under 想象 自然 end 今天要來介紹比較好玩的內容——__index元方法 1.我是備胎,記得回頭看看 咳咳,相信每一位女生都擁有或者不知不覺中擁有了一些備胎,啊,當然,又或許是成為過別人的備胎。 沒有備胎的人,就不是完整的人生。(

maven手動將jar安裝進倉庫的方法及問題

maven 眾所周知,我們只要在pom.xml文件中進行配置,maven就會自動下載jar包到本地倉庫,那麽,如果我們自己寫一個jar包自己用,那麽便無法通過配置來引用這個包,需要我們手動將包安裝進倉庫中。 我們使用命令mvn install:install-file -Dfile=your-j

maven如何打jar

www family 掃描 簡單的 plugin jar包 多個 for pro  Idea中為一般的非Web項目打Jar包是有自己的方法的,網上一搜就能查到很多。   但是如果是為Maven項目打Jar包,其實是很簡單的,因為maven本身就有打Jar包的命令。   

LaTeX 使用三級標題

ecn etc 需要 二級 set 使用 latex tar start 需要在導言區加入命令:\setcounter{secnumdepth}{4} 而後: \section{一級標題} \subsection{二級標題} \subsubsection{三

Swift 的Closures(閉)詳解

mount light sca ring 需要 line rem sin 代碼 Swift 中的Closures(閉包)詳解 在Swift沒有發布之前,所有人使用OC語言編寫Cocoa上的程序,而其中經常被人們討論的其中之一 -- Block 一直備受大家的喜愛。在Swif