center title in latex-rendered text for matplotlib figure

  • Last Update :
  • Techknowledgy :

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()

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()

Suggestion : 2

When I input the previously cited lines, I anycodings_latex get no title output at all on the figure. I anycodings_latex do not have a LaTeX error on the python anycodings_latex command interpreter though.,I would like to center a title for a anycodings_latex Matplotlib figure which includes a newline anycodings_latex return (\) when rendering it LaTeX style ,inserting a simple return code for latex \\ anycodings_latex in the middle of the title will work, but anycodings_latex will not have it centered so that the anycodings_latex newline is awkwardly shifted from the first anycodings_latex line.,You can easily use \n to get newline anycodings_latex within plt.title():

inserting a simple return code for latex \\ anycodings_latex in the middle of the title will work, but anycodings_latex will not have it centered so that the anycodings_latex newline is awkwardly shifted from the first anycodings_latex 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}")

You can easily use \n to get newline anycodings_latex 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()

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()

Suggestion : 3

You can use TeX to render all of your Matplotlib text by setting rcParams["text.usetex"] (default: False) to True. This requires that you have TeX and the other dependencies described in the Text rendering with LaTeX tutorial properly installed on your system. Matplotlib caches processed TeX expressions, so that only the first occurrence of an expression triggers a TeX compilation. Later occurrences reuse the rendered image from the cache and are thus faster., Rendering math equations using TeX , Showcase Anatomy of a figure Bachelor's degrees by gender Firefox Integral as the area under a curve Shaded & power normalized rendering XKCD , Demonstrates plotting contour (level) curves in 3D using the extend3d option

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True

t = np.linspace(0.0, 1.0, 100)
s = np.cos(4 * np.pi * t) + 2

fig, ax = plt.subplots(figsize = (6, 4), tight_layout = True)
ax.plot(t, s)

ax.set_xlabel(r '\textbf{time (s)}')
ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}', fontsize = 16)
ax.set_title(r '\TeX\ is Number $\displaystyle\sum_{n=1}^\infty'
   r '\frac{-e^{i\pi}}{2^n}$!', fontsize = 16, color = 'r')
Text(0.5, 1.0652809399537557, '\\TeX\\ is Number $\\displaystyle\\sum_{n=1}^\\infty\\frac{-e^{i\\pi}}{2^n}$!')
fig, ax = plt.subplots()
# interface tracking profiles
N = 500
delta = 0.6
X = np.linspace(-1, 1, N)
ax.plot(X, (1 - np.tanh(4 * X / delta)) / 2, # phase field tanh profiles X, (1.4 + np.tanh(4 * X / delta)) / 4, "C2", # composition profile X, X < 0, "k--") # sharp interface

# legend
ax.legend(("phase field", "level set", "sharp interface"),
   shadow = True, loc = (0.01, 0.48), handlelength = 1.5, fontsize = 16)

# the arrow
ax.annotate("", xy = (-delta / 2., 0.1), xytext = (delta / 2., 0.1),
   arrowprops = dict(arrowstyle = "<->", connectionstyle = "arc3"))
ax.text(0, 0.1, r "$\delta$",
   color = "black", fontsize = 24,
   horizontalalignment = "center", verticalalignment = "center",
   bbox = dict(boxstyle = "round", fc = "white", ec = "black", pad = 0.2))

# Use tex in labels
ax.set_xticks([-1, 0, 1])
ax.set_xticklabels(["$-1$", r "$\pm 0$", "$+1$"], color = "k", size = 20)

# Left Y - axis labels, combine math mode and text mode
ax.set_ylabel(r "\bf{phase field} $\phi$", color = "C0", fontsize = 20)
ax.set_yticks([0, 0.5, 1])
ax.set_yticklabels([r "\bf{0}", r "\bf{.5}", r "\bf{1}"], color = "k", size = 20)

# Right Y - axis labels
ax.text(1.02, 0.5, r "\bf{level set} $\phi$",
   color = "C2", fontsize = 20, rotation = 90,
   horizontalalignment = "left", verticalalignment = "center",
   clip_on = False, transform = ax.transAxes)

# Use multiline environment inside a `text`.
# level set equations
eq1 = (r "\begin{eqnarray*}"
   r "|\nabla\phi| &=& 1,\\"
   r "\frac{\partial \phi}{\partial t} + U|\nabla \phi| &=& 0 "
   r "\end{eqnarray*}")
ax.text(1, 0.9, eq1, color = "C2", fontsize = 18,
   horizontalalignment = "right", verticalalignment = "top")

# phase field equations
eq2 = (r "\begin{eqnarray*}"
   r "\mathcal{F} &=& \int f\left( \phi, c \right) dV, \\ "
   r "\frac{ \partial \phi } { \partial t } &=& -M_{ \phi } "
   r "\frac{ \delta \mathcal{F} } { \delta \phi }"
   r "\end{eqnarray*}")
ax.text(0.18, 0.18, eq2, color = "C0", fontsize = 16)

ax.text(-1, .30, r "gamma: $\gamma$", color = "r", fontsize = 20)
ax.text(-1, .18, r "Omega: $\Omega$", color = "b", fontsize = 20)

plt.show()

Suggestion : 4

Often in statistical data visualization, all you want is to plot histograms and joint distributions of variables. We have seen that this is relatively straightforward in Matplotlib (Figure 4-113):,Although Matplotlib is the most prominent Python visualization library, there are other more modern tools that are worth exploring as well. I’ll mention a few of them briefly here:,This type of flexibility in the plt.plot function allows for a wide variety of possible visualization options. For a full description of the options available, refer to the plt.plot documentation.,Matplotlib’s API is relatively low level. Doing sophisticated statistical visualization is possible, but often requires a lot of boilerplate code.

Just as we use the np shorthand for NumPy and the pd shorthand for Pandas, we will use some standard shorthands for Matplotlib imports:

In[1]: import matplotlib as mpl
import matplotlib.pyplot as plt

We will use the plt.style directive to choose appropriate aesthetic styles for our figures. Here we will set the classic style, which ensures that the plots we create use the classic Matplotlib style:

In[2]: plt.style.use('classic')

So, for example, you may have a file called myplot.py containing the following:

#-- -- -- - file: myplot.py-- -- --
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))

plt.show()

You can then run this script from the command-line prompt, which will result in a window opening with your figure displayed:

$ python myplot.py

It can be very convenient to use Matplotlib interactively within an IPython shell (see Chapter 1). IPython is built to work well with Matplotlib if you specify Matplotlib mode. To enable this mode, you can use the %matplotlib magic command after starting ipython:

In[1]: % matplotlib
Using matplotlib backend: TkAgg

In[2]: import matplotlib.pyplot as plt

For this book, we will generally opt for %matplotlib inline:

In[3]: % matplotlib inline

After you run this command (it needs to be done only once per kernel/session), any cell within the notebook that creates a plot will embed a PNG image of the resulting graphic (Figure 4-1):

In[4]: import numpy as np
x = np.linspace(0, 10, 100)

fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--');

One nice feature of Matplotlib is the ability to save figures in a wide variety of formats. You can save a figure using the savefig() command. For example, to save the previous figure as a PNG file, you can run this:

In[5]: fig.savefig('my_figure.png')

We now have a file called my_figure.png in the current working directory:

In[6]: !ls - lh my_figure.png
In[6]: !ls -lh my_figure.png
-rw - r--r--1 jakevdp staff 16 K Aug 11 10: 59 my_figure.png

In savefig(), the file format is inferred from the extension of the given filename. Depending on what backends you have installed, many different file formats are available. You can find the list of supported file types for your system by using the following method of the figure canvas object:

In[8]: fig.canvas.get_supported_filetypes()
In[8]: fig.canvas.get_supported_filetypes()
Out[8]: {
   'eps': 'Encapsulated Postscript',
   'jpeg': 'Joint Photographic Experts Group',
   'jpg': 'Joint Photographic Experts Group',
   'pdf': 'Portable Document Format',
   'pgf': 'PGF code for LaTeX',
   'png': 'Portable Network Graphics',
   'ps': 'Postscript',
   'raw': 'Raw RGBA bitmap',
   'rgba': 'Raw RGBA bitmap',
   'svg': 'Scalable Vector Graphics',
   'svgz': 'Scalable Vector Graphics',
   'tif': 'Tagged Image File Format',
   'tiff': 'Tagged Image File Format'
}