简体   繁体   中英

Using LaTeX in matplotlib

I try to make a table with a title in Python using LaTeX.

The following code creates a figure with a title, as I want the title to be.

import matplotlib.pyplot as plt

s1="a_b_c"
s2=r'''\begin{tabular}{ c | c | c } & 1 & 2 \\\hline 1 & 1 & 2 \\\hline 2 & 2 & 4 \end{tabular}'''

plt.figure(figsize=(4,5))
ax=plt.subplot2grid((1,1),(0,0))

ax.text(0.5,0.8,s1,ha="center",va="center",transform=ax.transAxes)

plt.show()

正确的标题

But now I add two lines to the upper code which make the title wrong.

import matplotlib.pyplot as plt

s1="a_b_c"
s2=r'''\begin{tabular}{ c | c | c } & 1 & 2 \\\hline 1 & 1 & 2 \\\hline 2 & 2 & 4 \end{tabular}'''

plt.figure(figsize=(4,5))
ax=plt.subplot2grid((1,1),(0,0))

ax.text(0.5,0.8,s1,ha="center",va="center",transform=ax.transAxes)

###
plt.rc('text', usetex=True)
ax.text(0.3,0.2,s2,ha="left",va="bottom",transform=ax.transAxes,size=20)
###

plt.show()

在此处输入图片说明

What can I do to use LaTeX fonts and usual python fonts at the same time? Of course, without modifying the strings s1 and s2.

All you need to do is add a few lines to your file:

import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
plt.rc('font', family='serif')

And you have LaTeX fonts!

To get the a_b_c working like you wanted, you need to do:

a_{b_c}

Or the b and c will be at the same level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM