Matplotlib:textcolor 不显示任何颜色

Matplotlib: textcolor doesn't show any colors

我正在使用 matplotlib 3.4.3ubuntu 20.04Python 3.8 。我试图用多色更改标签颜色,但它显示黑色且没有任何错误。我已经安装了所有软件包和 tried differents examples 但没有成功。另外,我有多个标签需要不同的颜色,这使得手动排列它们变得困难。

sudo apt-get install texlive-latex-base texlive-fonts-recommended texlive-fonts-extra texlive-latex-extra

import matplotlib.pyplot as plt


plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] =r"\usepackage{xcolor} "
_, ax = plt.subplots()

plt.plot([0, 1], [0, 1], 'r')
plt.plot([0, 1], [0, 2], 'b')


plt.ylabel(r"\color{blue}{y} "+r"\textcolor{red}{label} ")

plt.savefig('test.pdf')
plt.show()

这似乎是许多 matplotlib 后端的已知问题。例如,参见此处:https://github.com/matplotlib/matplotlib/issues/6724

一个可能的解决方案,如 suggested here,是以 ps 格式保存图形,稍后再转换为 pdf

例如:

import matplotlib.pyplot as plt


plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] =r"\usepackage{xcolor} "
_, ax = plt.subplots()

plt.plot([0, 1], [0, 1], 'r')
plt.plot([0, 1], [0, 2], 'b')


plt.ylabel(r"\color{blue}{y} "+r"\textcolor{red}{label} ")

plt.savefig('test.ps')

然后,在终端中

ps2pdf test.ps

下面是生成的 test.pdf 文件的屏幕截图:

注意:在 python 3.7.10matplotlib 3.4.2MacOS 10.15.7

上测试

only support the ps format. So, I tried to solve the problem to accept any format. To show how I solve this problem, I provide a dataset that makes the whole idea sample to understand. In my case, I have more than 34 figures with different points, and every point needs to be described. I use this code 的答案,我添加了 x=min(x-axis)y=median(y-axis)

这里是emp.csv

的内容

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.transforms import Affine2D
import os
cwd = os.path.dirname(__file__)

def rainbow_text(x, y, strings, colors, orientation='vertical',
                 ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    t = ax.transData
    canvas = ax.figure.canvas

    assert orientation in ['horizontal', 'vertical']
    if orientation == 'vertical':
        kwargs.update(rotation=90, verticalalignment='bottom')

    for s, c in zip(strings, colors):
        text = ax.text(x, y, s + " ", color=c, transform=t, **kwargs)

        # Need to draw to update the text position.
        text.draw(canvas.get_renderer())
        ex = text.get_window_extent()
        if orientation == 'horizontal':
            t = text.get_transform() + Affine2D().translate(ex.width, 0)
        else:
            t = text.get_transform() + Affine2D().translate(0, ex.height)
df = pd.read_csv('emp.csv', error_bad_lines=False)
colors_ = ['black', 'red', 'black', 'red']
i=0
for row in df.itertuples(index=True, name='Pandas'):

    plt.scatter(getattr(row, "sal"), getattr(row, "inc"), color = 'b', s=10)
    word = ['First name=', str(getattr(row, "first_name")), 'Last name=', str(getattr(row, "last_name"))]
    rainbow_text(df["sal"].min()-8.3, df["inc"].median()-1.2, word, colors_, size=5)
    word = ['age=', str(getattr(row, "age")), 'gender=', str(getattr(row, "gender"))]
    rainbow_text(df["sal"].min()-7.8, df["inc"].median()-1.2, word, colors_, size=5)
    plt.savefig(os.path.join(cwd, 'fig/Test_fig_' + str(i) + '.pdf'), format='pdf', dpi=600, bbox_inches='tight')
    i += 1
    plt.show()