Make Part of a Matplotlib Title Bold and a Different Color

Make part of a matplotlib title bold and a different color

activate latex text rendering

from matplotlib import rc
rc('text', usetex=True)

plt.title("This is title number: " + r"\textbf{" + str(number) + "}")

Display some text as bold using matplotlib

This is one way of doing it. You just have to convert the DataFrame value to string


Complete answer

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'price': [2, 4, 8, 3]}, index=['A', 'B', 'C', 'D'])

fig = plt.figure()

plt.text(0.1,0.9, r"The price for this month is: "+ r"$\bf{USD\$" + str(df.price.iloc[-1]) + "}$")
plt.show()

Sample Image

Even concise:

plt.text(0.1,0.9, r"The price for this month is: $\bf{USD\$ %s}$" % str(df.price.iloc[-1]) )

You can also use formatting as

fig = plt.figure()

plt.text(0.1,0.9, r"The price for this month is: " + r"$\bf{USD\$" + '{:.2f}'.format(df.price.iloc[-1]) + "}$")

Sample Image

Bold some but not all characters of plot title

Try this:

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot([1,2,3])
ax2.plot([-1,-2,-3])

# ax1 = plt.gca()
ax1.set(title=r'$\bf{A}$. line with positive slope')
ax2.set(title=r'$\bf{B}$. line with negative slope')

Sample Image

Bold title - subplots

Try:

def setBold(txt): return r"$\bf{" + str(txt) + "}$"

plt.title(setBold("AAAAA") + '\n' + setBold('+'))

The problem comes from "\n". Putting newline in matplotlib label with TeX advices seperating the \n from the Latex formatting.

Hope that helps!

How to bold a single word in a string of text in matplotlib?

You can instruct matplotlib to use LaTeX for text formatting: https://matplotlib.org/stable/tutorials/text/usetex.html

plt.rc('text', usetex=True)
text = r"This is text. I want the word '\textbf{blah}' to be Bold."

Sample Image

Legend format - make bold border, or bigger / different font

You can use the loc keyword for plt.legend():

plt.legend(['Group A','Group B','Group C'], loc=(1.04, 1))

Output:Sample Image

Styling part of label in legend in matplotlib

As silvado mentions in his comment, you can use LaTeX rendering for more flexible control of the text rendering. See here for more information: http://matplotlib.org/users/usetex.html

An example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc

# activate latex text rendering
rc('text', usetex=True)

x = np.arange(10)
y = np.random.random(10)
z = np.random.random(10)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, label = r"This is \textbf{line 1}")
ax.plot(x, z, label = r"This is \textit{line 2}")
ax.legend()
plt.show()

Sample Image

Note the 'r' before the strings of the labels. Because of this the \ will be treated as a latex command and not interpreted as python would do (so you can type \textbf instead of \\textbf).



Related Topics



Leave a reply



Submit