Gök*_*ver 38 python matplotlib
matplotlib中有一种方法可以部分指定字符串的颜色吗?
例:
plt.ylabel("Today is cloudy.")
Run Code Online (Sandbox Code Playgroud)
如何将"今天"显示为红色,"是"显示为绿色和"阴天".如蓝色?
谢谢.
Yan*_*ann 24
我只知道如何以非交互方式进行此操作,即使只有'PS'后端.
为此,我将使用Latex格式化文本.然后我会包含'颜色'包,并根据需要设置颜色.
这是一个这样做的例子:
import matplotlib
matplotlib.use('ps')
from matplotlib import rc
rc('text',usetex=True)
rc('text.latex', preamble='\usepackage{color}')
import matplotlib.pyplot as plt
plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
r'\textcolor{green}{is} '+
r'\textcolor{blue}{cloudy.}')
plt.savefig('test.ps')
Run Code Online (Sandbox Code Playgroud)
这导致(使用ImageMagick从ps转换为png,所以我可以在这里发布):

Pau*_*nov 21
这是交互式版本(我发布到列表中的同一个版本)
import matplotlib.pyplot as plt
from matplotlib import transforms
def rainbow_text(x,y,ls,lc,**kw):
"""
Take a list of strings ``ls`` and colors ``lc`` and place them next to each
other, with text ls[i] being shown in color lc[i].
This example shows how to do both vertical and horizontal text, and will
pass all keyword arguments to plt.text, so you can set the font size,
family, etc.
"""
t = plt.gca().transData
fig = plt.gcf()
plt.show()
#horizontal version
for s,c in zip(ls,lc):
text = plt.text(x,y," "+s+" ",color=c, transform=t, **kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
#vertical version
for s,c in zip(ls,lc):
text = plt.text(x,y," "+s+" ",color=c, transform=t,
rotation=90,va='bottom',ha='center',**kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
plt.figure()
rainbow_text(0.5,0.5,"all unicorns poop rainbows ! ! !".split(),
['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'],
size=40)
Run Code Online (Sandbox Code Playgroud)

延伸Yann的答案,LaTeX着色现在也适用于PDF导出:
import matplotlib
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
import matplotlib.pyplot as plt
pgf_with_latex = {
"text.usetex": True, # use LaTeX to write all text
"pgf.rcfonts": False, # Ignore Matplotlibrc
"pgf.preamble": [
r'\usepackage{color}' # xcolor for colours
]
}
matplotlib.rcParams.update(pgf_with_latex)
plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
r'\textcolor{green}{is} '+
r'\textcolor{blue}{cloudy.}')
plt.savefig("test.pdf")
Run Code Online (Sandbox Code Playgroud)
请注意,此python脚本有时会Undefined control sequence在第一次尝试时失败并显示错误.然后再次运行它是成功的.
| 归档时间: |
|
| 查看次数: |
15349 次 |
| 最近记录: |