无法为LaTeX字符串中的特定字符呈现不同的颜色
我需要更改绘图标题的LaTeX字符串中子字符串的颜色。我尝试了几种不同的方法,其中大多数给出了错误和/或警告。下面的代码不提供任何错误或警告,但不会呈现指定的颜色。
# -*- 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()
答案 0 :(得分:1)
最简单的方法是
t = ax.set_title("red")
t.set_color("r")
一个完整的例子,
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()
更新:
这种带有文本的想法可用于在单个单词中获得不同的颜色,尽管不是理想的解决方案,因为您必须将各种字母排列在一起,
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")
您可以将此功能设为example中的标题,
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()