简体   繁体   中英

How to render substrings of a LaTeX string, in different colors in matplotlib?

Unable to render different colors for specific characters within a LaTeX string

I need to change the color of substrings within a LaTeX string for a plot title. I have tried several different approaches, most of which gave errors and/or warnings. The code below gives no errors or warnings, but does not render the color specified.

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib
matplotlib.use("WXAgg")
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble = r'\usepackage{xcolor}')

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

fig, ax = plt.subplots()
ax.scatter(x, np.cos(x), color = 'blue', marker = "+", s=47.5)
ax.set_title(r'$\color{red}{X}X$') 
#ax.set_title(r"\textcolor{red}{X} $\color{red}{X}$") # does not work either

plt.show()

The easiest way is,

t = ax.set_title("red")
t.set_color("r")

A complete example,

import numpy as np
import matplotlib
matplotlib.use("WXAgg")
import matplotlib.pyplot as plt

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


N = 50
x = np.random.rand(N)
y = np.random.rand(N)

fig, ax = plt.subplots()
ax.scatter(x, np.cos(x), color = 'blue', marker = "+", s=47.5)
t = ax.set_title(r"X $X$")
t.set_color("r")

plt.show()

UPDATE:

This idea with text can be used to get different colours in a single word, although not an ideal solution as you have to line the various letters up,

t1 = fig.text(0.5,0.9,"$X$", transform=ax.transAxes)
t1.set_color("r")
t2 = fig.text(0.515,0.9,"$X$", transform=ax.transAxes)
t2.set_color("b")

You can make this a function, as in this example adapted for the title,

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker

def multicolor_label(ax, list_of_strings, list_of_colors, anchorpad=0, **kw):
    boxes = [TextArea(text, textprops=dict(color=color, ha='left',va='bottom',**kw)) 
                for text,color in zip(list_of_strings,list_of_colors) ]
    xbox = HPacker(children=boxes,align="center",pad=0, sep=5)
    anchored_xbox = AnchoredOffsetbox(loc=3, child=xbox, pad=anchorpad, frameon=False, 
                                      bbox_to_anchor=(0.5, 1.0), 
                                      bbox_transform=ax.transAxes, borderpad=0.)
    ax.add_artist(anchored_xbox)

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

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

fig, ax = plt.subplots()
ax.scatter(x, np.cos(x), color = 'blue', marker = "+", s=47.5)
multicolor_label(ax, ["$X$", "$X$"], ["r", "b"])
plt.show()

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