裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

pweave で R の xtable 相当の機能を装備する(その2, Python)

2020年11月25日 | Python

まったく。

日本語(utf-8)が使えないのは,Pweave.engine で経験・解決済みだろ。

ということで,xtable 関数に原因があるわけではないので,それを呼び出す前に locale をセットする必要があるということ。

* 使用法:

setlocale は,xtable の定義の後に実行されているので,普通は再度設定する必要はない。

xtable の引数は,
    xtable(x, caption, label, fmt, align, pos="htbp")

x    pandas のデータフレームオブジェクト caption 表のキャプション
label    table 環境につけるラベル。
    label+".tex" という名前でファイルが作られるので,必要なところで \input{*} で読み込む。
fmt    表の各列の形式を指定するリスト
    文字列なら "s",数値なら小数部の桁数 "3" など,整数なら "0" または "d" を指定 する。
    表の列あたり 1 文字ずつ,全部で表の列数ぶんの長さの文字列で指定(例 "s053"
align    各列での配置法を表す 1 つの文字列(長さは表の列数に等しい) 例 "rllcr"
pos    表の位置。デフォルトは "htbp"

* 使用例

<<>>=
import pandas as pd x = pd.DataFrame({
"a" : [1,2,3,4,5],
"b" : [1.1,2.2,3.3,4.5,5.5], "c" : ["a", "b", "c", "d", "e"] })
xtable(x, "xtable 使用例", "label", "d1s", "rrr")
@

\input{labe.tex}

* xtable

<<>>=
def xtable(x, caption, label, fmt, align, pos="htbp"):
    import scipy as sp
    colnames = x.columns
    f = open(label+".tex", "w")
    x = sp.array(x)
    n = x.shape
    print("\\begin{{table}}[{0:s}]". format(pos), file=f)
    print("\\begin{center}", file=f)
    print("\\caption{{{0:s}}}". format(caption), file=f)
    print("\\label{{{0:s}}}". format(label), file=f)
    print("\\begin{{tabular}}{{{0:s}}} \\hline". format(align), file=f)
    for i in range(n[0]):
        if i == 0:
            for j in range(n[1]):
                print("{0:s}". format(colnames[j]), end="", file=f)
                if j == n[1]-1:
                    print(" \\\\ \\hline", file=f)
                else:
                    print(" & ", end="", file=f)
        for j in range(n[1]):
            if fmt[j] == "s":
                print("{0:s}". format(x[i,j]), end="", file=f)
            elif fmt[j] == "d":
                print("{0:d}". format(int(x[i,j])), end="", file=f)
            else:
                digits = int(fmt[j])
                print("{1:.{0:d}f}". format(digits, float(x[i,j])), end="", file=f)
            if j == n[1]-1:
                print(" \\\\", end="", file=f)
            else:
                print(" & ", end="", file=f)
        if i == n[0]-1:
            print(" \\hline", file=f)
        else:
            print(file=f)
    print("\\end{tabular}", file=f)
    print("\\end{center}", file=f)
    print("\\end{table}", file=f)
    f.close()

import locale
locale.setlocale(locale.LC_ALL, "ja_JP.UTF-8")
@

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

matplotlib で日本語を使えるようにする(Mac, Python)

2020年11月25日 | Python

matplotlib で日本語を使えるようにする

Mac の場合,デフォルトで使える日本語フォントは AppleGothic である。まずは,これを使ってみる。

matplotlib のさまざまな設定は,matplotlibrc ファイルに書いてある。このファイルで,使うフォントの設定を日本語フォントを使うように書き換えればよい。

matplotlibrc は,Python で以下のようにすれば分かる。

>>>> import matplotlib as mpl
>>>> mpl.matplotlib_fname()

表示されたパスが /usr/local/Cellar/python3/途中省略/matplotlib/mpl-data/matplotlibrc のようなものだとすれば,それは,Python がインストールされたときに自動的に作られたものである。まずこれを自分のホームディレクトリへコピーする。

コンソール(ターミナル)で
$ cp /usr/local/Cellar/python3/途中省略/matplotlib/mpl-data/matplotlibrc ̃/.matplotlib/
とすれば,自分のホームディレクトリの .matplotlib の下に matplotlibrc がコピーされる。

この時点で再度,

>>>> import matplotlib as mpl
>>>> mpl.matplotlib_fname()

としたとき,/Users/foo/.matplotlib/matplotlibrc のようになることを確認しよう。

コピーされた matplotlibrc をエディタで開き,以下のように font.serif,font.sans-serif を含む行の先頭の # を削除して,フォントリストの先頭に AppleGothic を加える。

その他の設定も自分好みに変更してもよい。


#font.serif       : DejaVu Serif, Bitstream Vera Serif, 以下略
#font.sans-serif  : DejaVu Sans, Bitstream Vera Sans, 以下略


font.serif       : AppleGothic, DejaVu Serif, Bitstream Vera Serif, 以下略
font.sans-serif  : AppleGothic, DejaVu Sans, Bitstream Vera Sans, 以下略

設定が終わったら,以下のプログラムを実行してみる。

>>>> df = pd.DataFrame(np.array([[1,2,3,4,5,6], [3,6,7,4,8,9]]).T, columns = ['月','製品A'])
>>>> df.plot(kind = 'line', x = '月', y = '製品A').set(ylabel = '売上')

もしフォントが気に入らなければ(注1),「IPA フォント ダウンロードページ」〔注2)から,TTF ファイルの「4 書体パック (Ver.003.03) IPAfont00303.zip」をダウンロード・展開する。

Mac の場合,展開された 4 ファイルを,ライブラリ/Fonts ディレクトリへ移動する。

4 つの書体の名前,IPAPGothic,IPAGothic,IPAPMincho,IPAMincho から,いずれかを選んで,上述の matplotlibrc に設定する〔注3)。

======================================================================

(注1)一部の漢字が用意されていない?例えば「売」はトーフになる。
(注2)http://ipafont.ipa.go.jp/old/ipafont/download.html
(注3)上の図のフォントは IPAMincho である。

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

pweave で R の xtable 相当の機能を装備する(Python)

2020年11月25日 | Python

pweave のチャンクではまだ results=tex がサポートされていない,まあ何とかすることはできるだろうと思ってやってみた

ただし,関数で *.tex ファイルを保存して \input{*} で読み込もうという手はず。

<<>>=
def xtable(x, caption, label, fmt, align, pos="htbp"):
    import scipy as sp
    colnames = x.columns
    f = open("test.tex", "w")
    x = sp.array(x)
    n = x.shape
    print("\\begin{{table}}[{0:s}]". format(pos), file=f)
    print("\\begin{center}", file=f)
    print("\\caption{{{0:s}}}". format(caption), file=f)
    print("\\label{{{0:s}}}". format(label), file=f)
    print("\\begin{{tabular}}{{{0:s}}} \\hline". format(align), file=f)
    for i in range(n[0]):
        if i == 0:
            for j in range(n[1]):
                print("{0:s}". format(colnames[j]), end="", file=f)
                if j == n[1]-1:
                    print(" \\\\ \\hline", file=f)
                else:
                    print(" & ", end="", file=f)
        for j in range(n[1]):
            if fmt[j] == "s":
                print("{0:s}". format(x[i,j]), end="", file=f)
            elif fmt[j] == "d":
                print("{0:d}". format(int(x[i,j])), end="", file=f)
            else:
                digits = int(fmt[j])
                print("{1:.{0:d}f}". format(digits, float(x[i,j])), end="", file=f)
            if j == n[1]-1:
                print(" \\\\", end="", file=f)
            else:
                print(" & ", end="", file=f)
        if i == n[0]-1:
            print(" \\hline", file=f)
        else:
            print(file=f)
    print("\\end{tabular}", file=f)
    print("\\end{center}", file=f)
    print("\\end{table}", file=f)
    f.close()
@

という関数を定義しておいて,LaTeX で表示したいものを DataFrame にして,変換関数 xtable に渡し,ファイルに書いた LaTeX 形式のファイルを \input してタイプセットということで,

<<>>=
import pandas as pd
x = pd.DataFrame({
    "a" : [1,2,3,4,5],
    "b" : [1.1,2.2,3.3,4.5,5.5],
    "c" : ["a", "b", "c", "d", "e"]
    })

xtable(x, 'title', "label", ["3", "0", "s"], "rrr")
@
\input{test}

しかし,ここに落とし穴が。

 title を日本語で指定すると,だめになる。

Python  で utf-8 エンコーディングの日本語をファイルに書いてからそれを読む方法がわからん。

できないわけはないと思うが,できないなら Python の大チョンボだ。

どんなアプリでもプログラム言語でも,utf-8 文字列をファイルに書いて,それをどんなアプリでもプログラム言語でも,読み込んだらちゃんと utf-8 文字列になるというのは当たり前と思うが???

解決法を知っている方はお教えいただきたい。

#########################################

プログラムの先頭で,

    import locale
    locale.setlocale(locale.LC_ALL, "ja_JP.UTF-8")

のようなおまじないを唱えておくとよいようだ。

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村