首页 > 解决方案 > 在 xtick 标签中使用带有换行符的 tex 时,Matplotlib 无法生成绘图

问题描述

我正在生成一个具有多级 xtick 标签的图形。我可以通过使用带有换行符的额外标签来实现这一点。但是,如果我在绘图生成中使用 tex,则该方法不起作用,并且错误告诉我 tex.cache 中的 .dvi 文件丢失。我发现tex文件存在,但是latex没有生成dvi文件,因为没有页面可以生成。

使用 tex 时,如果我更改ax.set_xticklabels(labels + ["\nA to C"])ax.set_xticklabels(labels + ["A to C"])或,代码可以完美运行ax.set_xticklabels(labels + ["DummyText\nA to C"])

如何在 xtick 标签中使用带有换行符的 matplotlib+tex 成功生成图形?


import matplotlib.pyplot as plt
import matplotlib
import numpy

# There will be errors in code if I uncomment the following
# matplotlib.rc('text', usetex = True)

fig, axs = plt.subplots(1, 1, squeeze=False)
ax = axs[0, 0]
labels = ["A", "B", "C", "D", "E"]
data1 = [1,2,3,4,5]
data2 = [1.5,2.5,2.5,3.5,7]
total_categories = len(data1)

width = 1
data1_color = '#fc8d62'
data2_color = '#66c2a5'
props = {'connectionstyle':'bar','arrowstyle':'-',\
                 'shrinkA':20,'shrinkB':20,'linewidth':2}

center_positions = numpy.arange(0,total_categories) * 2.5
ax.bar(center_positions - 0.5, data1, width=width, color=data1_color, align='center', edgecolor='black', hatch='//', label="Data1")
ax.bar(center_positions + 0.5, data2, width=width, color=data2_color, align='center', edgecolor='black', label="Data2")

# Setting xticks
ax.set_xticks(numpy.concatenate((center_positions, numpy.array([2.5]))))
ax.set_xticklabels(labels + ["\nA to C"])
ax.set_xticks([-1.25, 6.25, 8.75, 11.25], minor=True)
ax.tick_params( axis='x', which='minor', direction='out', length= 45)
ax.tick_params( axis='x', which='major', bottom='off', top='off' )
ax.set_xlim(-1.25, 11.25)
ax.set_xlabel("Methods", size=15)

ax.legend()
fig.savefig("Temp.pdf")

目标输出

% tex file auto generated by matplotlib
\documentclass{article}
\usepackage{type1cm}



\usepackage{textcomp}

\usepackage[utf8]{inputenc}

\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
\pagestyle{empty}
\begin{document}
\fontsize{10.000000}{12.500000}{\sffamily } % When there are other texts, a dvi file will be generated
\end{document}

标签: pythonmatplotlib

解决方案


推荐阅读