简体   繁体   中英

Center title in latex-rendered text for matplotlib figure

I would like to center a title for a Matplotlib figure which includes a newline return (\\) when rendering it LaTeX style

inserting a simple return code for latex \\\\ in the middle of the title will work, but will not have it centered so that the newline is awkwardly shifted from the first line.

from matplotlib import pyplot as plt
plt.rc('text', usetex=True)
plt.title(r"\center{\textbf{Some title \\ with with a newline}}")

or

plt.title(r"\begin{centering}{\textbf{Some title \\ with a newline}\end{centering}")

won't work

When I input the previously cited lines, I get no title output at all on the figure. I do not have a LaTeX error on the python command interpreter though.

You can easily use \\n to get newline within plt.title() :

import numpy as np
import matplotlib.pyplot as plt

plt.rc('text', usetex=True)

t = np.arange(0., 5., 0.2)

plt.plot(t, t/5000,)
plt.title(r"$\textbf{Some title}$"
          "\n"
          r"$\textbf{with a formula}:$"
          "\n"
          r"$y=t/5000$")
plt.show()

在此处输入图片说明

Assuming you have a proper LaTex installed on your system, and all set up to use LaTex from within matplotlib, you have to set a specific LaTex preamble in which /begin{center} ... /end{center} is available.

Here is a working example.

import numpy as np
import matplotlib
matplotlib.rcParams['text.usetex'] = True
import matplotlib.pyplot as plt

custom_preamble = {                                                                          
    "text.latex.preamble":                                                                   
        r"\usepackage{amsmath}" # for the align, center,... environment
        ,
    }   
plt.rcParams.update(custom_preamble)                                                         
plt.figure(figsize= (6,4),tight_layout = True)                                               

t = np.linspace(0.0, 1.0, 100)
s = np.cos(4 * np.pi * t) + 2
plt.plot(t, s,label='your legend')

plt.xlabel(r'\textbf{bold (s)}')                                                        
plt.ylabel('\\textit{italic (\N{DEGREE SIGN}/sec)}', fontsize=16)                   
plt.title(r'\begin{center}Your title\\ new line, centered: ($-e^{i\pi}$, centered\end{center}')                  
plt.legend()
plt.show()

This gives:

在此处输入图片说明

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