gpt4 book ai didi

python - 为 pandas 绘图函数创建与 tex 兼容的名称

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:48 25 4
gpt4 key购买 nike

假设我绝对需要使用 tex 来生成图形的文本,并且我使用以下代码:

#!/usr/bin/env python3

import matplotlib as mpl
mpl.use("PDF")
from matplotlib.backends.backend_pgf import FigureCanvasPgf
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


# https://stackoverflow.com/a/42768093/1878788
mpl.backend_bases.register_backend('pdf', FigureCanvasPgf)
TEX_PARAMS = {
"text.usetex": True, # use LaTeX to write all text
"pgf.rcfonts": False, # Ignore Matplotlibrc
"pgf.texsystem": "lualatex", # hoping to avoid memory issues
}
mpl.rcParams.update(TEX_PARAMS)


def main():
data = pd.DataFrame({
"A1": np.random.randn(4),
"B1": np.random.randn(4),
"A2": np.random.randn(4),
"B2": np.random.randn(4)})
data.plot.box()
plt.savefig("test_tex_boxplot.pdf")


if __name__ == "__main__":
exit(main())

这有效。

现在,如果我的 DataFrame 中的列名称包含下划线(A_1 而不是 A1),则 tex 失败:

RuntimeError: LaTeX was not able to process the following string:
b'A_1'

我该如何解决这个问题?

最佳答案

一种解决方案是在调用绘图函数之前通过转义下划线来更改列名称:

#!/usr/bin/env python3

import matplotlib as mpl
mpl.use("PDF")
from matplotlib.backends.backend_pgf import FigureCanvasPgf
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from re import sub


# https://stackoverflow.com/a/42768093/1878788
mpl.backend_bases.register_backend('pdf', FigureCanvasPgf)
TEX_PARAMS = {
"text.usetex": True, # use LaTeX to write all text
"pgf.rcfonts": False, # Ignore Matplotlibrc
"pgf.texsystem": "lualatex", # hoping to avoid memory issues
}
mpl.rcParams.update(TEX_PARAMS)


def main():
data = pd.DataFrame({
"A_1": np.random.randn(4),
"B_1": np.random.randn(4),
"A_2": np.random.randn(4),
"B_2": np.random.randn(4)})
usetex = mpl.rcParams.get("text.usetex", False)
if usetex:
data.columns = [sub("_", "\_", colname) for colname in data.columns]
data.plot.box()
plt.savefig("test_tex_boxplot.pdf")


if __name__ == "__main__":
exit(main())

关于python - 为 pandas 绘图函数创建与 tex 兼容的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49136882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com