简体   繁体   English

matplotlib 图形的乳胶渲染文本的中心标题

[英]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我想将 Matplotlib 图形的标题居中,该图形在渲染 LaTeX 样式时包含换行符 (\\)

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.虽然我在 python 命令解释器上没有 LaTeX 错误。

You can easily use \\n to get newline within plt.title() :您可以轻松使用\\nplt.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.假设您的系统上安装了适当的 LaTex,并且所有设置都在 matplotlib 中使用 LaTex,您必须设置一个特定的 LaTex 前导码,其中/begin{center} ... /end{center}可用。

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:这给出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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