
Код Python, создающий промежуточный файл .pgf, выглядит следующим образом:
Код: Выделить всё
import matplotlib
import numpy
from matplotlib import pyplot
x = numpy.linspace(-1, 1)
y = x ** 2
matplotlib.rcParams["figure.figsize"] = (3, 2.5)
matplotlib.rcParams["font.family"] = "serif"
matplotlib.rcParams["font.size"] = 10
matplotlib.rcParams["legend.fontsize"] = 8
matplotlib.rcParams["pgf.texsystem"] = "lualatex"
PREAMBLE = r"""\usepackage{ifluatex}
\ifluatex
\usepackage{fontspec}
\setmainfont{lmroman10-regular.otf}
\fi
"""
matplotlib.rcParams["text.latex.preamble"] = PREAMBLE
matplotlib.rcParams["pgf.preamble"] = PREAMBLE
matplotlib.rcParams["text.usetex"] = True
pyplot.plot(x, y, label="this is the data")
pyplot.legend()
pyplot.xlabel("xlabel")
pyplot.tight_layout()
pyplot.savefig("lualatex_test.pgf")
Для этого простого примера файл .tex для визуализации .pgf может быть просто:
Код: Выделить всё
\documentclass[11pt]{scrbook}
\usepackage{pgf}
\usepackage{fontspec}
\setmainfont{lmroman10-regular.otf}
\newcommand{\mathdefault}[1]{#1}
\begin{document}
\input{lualatex_test.pgf}
\end{document}
I думал, что нашел причину этого, но, похоже, я что-то упустил. Как упоминалось выше, matplotlib вычисляет размеры текстовых фрагментов, фактически помещая их в шаблон латекса и компилируя его с помощью pdflatex. Это происходит, например, в классе matplotlib.texmanager.TexManager в соответствующем файле в основной ветке. Я думал, что смогу это исправить вот так:
Код: Выделить всё
class TexManager:
...
@classmethod
def get_text_width_height_descent(cls, tex, fontsize, renderer=None):
"""Return width, height and descent of the text."""
if tex.strip() == '':
return 0, 0, 0
dvifile = cls.make_dvi(tex, fontsize)
dpi_fraction = renderer.points_to_pixels(1.) if renderer else 1
with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
page, = dvi
# A total height (including the descent) needs to be returned.
w = page.width
# !!!
if tex == "this is the data":
w /= 1.14
print("fixed width")
# !!!
return w, page.height + page.descent, page.descent

Как решить эту проблему? Как matplotlib вычисляет ширину содержимого легенды и могу ли я исправить это, чтобы учесть правильную ширину? Предположим, я знаю, что коэффициент ошибки ширины для размера шрифта 8 составляет примерно 1,14. Я легко могу определить это для других шрифтов и размеров шрифтов.
Подробнее здесь: https://stackoverflow.com/questions/793 ... h-lualatex
Мобильная версия