LoginSignup
0
3

More than 5 years have passed since last update.

PythonTexで図を生成しGrid出力する

Last updated at Posted at 2019-02-03

概要

PythonTexを使うと、texの文書中にpythonのコードを埋め込むことができます。ここではtex文書中で図の作成とその表示・出力を行います。
特に図を連続出力したい場合にPythonTexがその実力を発揮するため、
複数の図を作成し、グリッドにして表示させます。

画像のGrid表示

今回は自動で出力した図をgridで表示するためにminipage環境を利用します。PythonTexを使わず、愚直に書くと以下のようなコードです。
たくさんの図を出力する際は非常に面倒ですね...

\begin{figure}[ht]
  \begin{minipage}[ht]{0.48\textwidth} 
    \centering 
    \includegraphics[width= 6 cm]{sin.png} 
    \caption{sin curve} 
    \label{sin} 
   \end{minipage} 
   \hfill
 \begin{minipage}[ht]{0.48\textwidth} 
...
 \end{minipage} 
\end{figure}

実行コード

特別なものとしてpythontexを指定します。
PythonTexの環境構築はこちらの記事が参考になります。

pycode環境にpythonのコードを埋め込み、
\py{}で呼び出すことでtex文書中に生成したtexコードを出力させます。

\documentclass{article}
\usepackage[dvipdfmx]{graphicx}
\usepackage{mediabb}
\usepackage{pythontex}
\begin{document}

\begin{pycode}
import matplotlib.pyplot as plt
import numpy as np

## 図の作成
def draw_func(x, y, name):
  plt.figure(figsize=(10, 7))
  plt.plot(x, y)
  plt.savefig('{}.png'.format(name))

def sin():
  x = np.arange(-3, 3, 0.01)
  y = np.sin(x)
  draw_func(x, y, 'sin')

def cos():
  x = np.arange(-3, 3, 0.01)
  y = np.cos(x)
  draw_func(x, y, 'cos')

def exp():
  x = np.arange(-3, 3, 0.01)
  y = np.exp(x)
  draw_func(x, y, 'exp')

def square():
  x = np.arange(-3, 3, 0.01)
  y = np.square(x)
  draw_func(x, y, 'square')

# ファイル名、caption, labelの指定
images = [ \
  ('sin.png', 'sin curve', 'sin'), \
  ('cos.png', 'cos curve', 'cos'), \
  ('exp.png', 'exp curve', 'exp'), \
  ('square.png', 'square curve', 'square'), \
  ]

def insert_grid_images(): # 2*N grid
  # 図の生成
  sin()
  cos()
  exp()
  square()

 # Gridで表示するためにfigure環境にminipageを作る
  head = r"\begin{figure}[ht]"
 
 # 反復部分
  content = ""
  for i in images:
    tmp = r"\
    \begin{minipage}[ht]{0.48\textwidth} \
      \centering \
      \includegraphics[width= 6 cm]{FILENAME} \
      \caption{CAPTION} \
      \label{LABEL} \
    \end{minipage} \
    \hfill"
    property = {
      "FILENAME" : i[0],
      "CAPTION" : i[1],
      "LABEL" : i[2],  
    }
    # ファイル名、caption, labelを置換
    for key, value in property.items():
      tmp = tmp.replace(key, value)

    content += tmp

  foot = r"\end{figure}"

 # 生成した文字列を返す
  return head+content+foot
\end{pycode}  


sin curve(Figure \ref{sin}), % 引用も可能
cos curve(Figure \ref{cos}), 
exp curve(Figure \ref{exp}), 
square curve(Figure \ref{square})

% ここでinsert_grid_images()を実行し、texのコードを出力する
\py{insert_grid_images()}


\end{document}

完成図

生成した図が 正しくgridで表示されています。tex本文中での引用もうまくいっています。

スクリーンショット 2019-02-03 17.04.39.png

参考

Tex Wiki PythonTex
TECH ACADEMY Pythonで複数箇所の文字列を置換する方法

リソース

こちらのリポジトリに実行コードがあります。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3