numpy.matrix
型の行列データがあります.これを行列の画像として出力したいのですが調べてもなかなか出てきません.numpy.array
型なら色々方法はあるみたいですが,numpy.matrix
型のデータに対して画像として出力,保存する方法はありますか?
以下がサンプルデータの一部です
A = np.matrix([
[0, 1, 1],
[1, 0, 1],
[1, 1, 0]
])
スタック・オーバーフローはプログラマーとプログラミングに熱心な人のためのQ&Aサイトです。すぐ登録できます。
登録してこのコミュニティに参加するnumpy.matrix
型の行列データがあります.これを行列の画像として出力したいのですが調べてもなかなか出てきません.numpy.array
型なら色々方法はあるみたいですが,numpy.matrix
型のデータに対して画像として出力,保存する方法はありますか?
以下がサンプルデータの一部です
A = np.matrix([
[0, 1, 1],
[1, 0, 1],
[1, 1, 0]
])
pandas
にto_latex()
というメソッドがあって、PyLaTeX
と(さらにLaTexのコンパイラと)組み合わせると、目的のものが出来そうです。こちらの記事に出ていました。
how to print a data frame from pandas using pylatex
上記記事で承認後にもっと簡単に出来るよ、と付いた回答の方ですね。
It might be noted, that pandas DataFrames already have a quite powerful
to_latex
method. Another approach that makes use of this method and does not reinvent the wheel would be:pandas DataFramesにはすでに非常に強力なto_latexメソッドがあることに注意してください。 この方法を利用し、車輪を再発明しない別のアプローチは次のとおりです。
import numpy as np import pylatex as pl import pandas as pd df = pd.DataFrame({'a': [1,2,3], 'b': [9,8,7]}) df.index.name = 'x' M = np.matrix(df.values) doc = pl.Document() doc.packages.append(pl.Package('booktabs')) with doc.create(pl.Section('Matrix')): doc.append(pl.Math(data=[pl.Matrix(M)])) # Difference to the other answer: with doc.create(pl.Section('Table')): with doc.create(pl.Table(position='htbp')) as table: table.add_caption('Test') table.append(pl.Command('centering')) table.append(pl.NoEscape(df.to_latex(escape=False))) doc.generate_pdf('full', clean_tex=False)
ちなみにPyLaTeX
を入れるだけだと、回答の様には出来なくて、最後の行でLaTexコンパイラが必要というエラーが出てきます。
>>> doc.generate_pdf('full', clean_tex=False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\pylatex\document.py", line 280, in generate_pdf
'Either specify a LaTex compiler ' +
pylatex.errors.CompilerError: No LaTex compiler was found
Either specify a LaTex compiler or make sure you have latexmk or pdfLaTex installed.
ただし以下のようにデータは出来ているようなので、上記エラーメッセージのようにLaTexコンパイラを入れれば目的は達成できるのではないでしょうか。
>>> doc
Document('default_filepath', [Command('normalsize', Arguments(), Options()), Section('Matrix', True, [Math([Matrix(matrix([[1, 9],
[2, 8],
[3, 7]], dtype=int64), [])])]), Section('Table', True, [Table([Command('caption', Arguments('Test'), Options()), Command('centering', Arguments(), Options()), NoEscape(\begin{tabular}{lrr}
\toprule
{} & a & b \\
x & & \\
\midrule
0 & 1 & 9 \\
1 & 2 & 8 \\
2 & 3 & 7 \\
\bottomrule
\end{tabular}
)])])])
関連:
pandas.DataFrame.to_latex
PyLaTeX - PyPl
Docs » PyLaTeX
他にはこんなツールもあるようです。
LaTeXの出力を多様な画像形式にするTeX2img
TeX2img配布サイト