【问题标题】:Matplotlib: textcolor doesn't show any colorsMatplotlib:textcolor 不显示任何颜色
【发布时间】:2021-10-18 09:24:39
【问题描述】:

我正在使用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()

【问题讨论】:

  • 谢谢,我试过了,它在问题中显示的链接上,它可以工作,但它与我需要的不匹配,因为循环中的每个点都需要有不同颜色的标签。
  • @tmdavison 如何使它为plt.ylabel 着色,因为它显示的文本不在标签中。
  • 在我看来,y 标签不是由 TeX 呈现的,请查看使用的字体。
  • 是乳​​胶的;它使用的是无衬线字体,而刻度标签使用的是衬线字体。尝试在 y 标签中添加一些数学模式文本进行检查(例如,在 $$ 之间添加一些内容)

标签: python-3.x matplotlib latex


【解决方案1】:

这似乎是许多 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 上测试

【讨论】:

  • 你也可以使用 pgf 后端:plt.savefig("test.pdf", use='pgf') 工作正常
  • 感谢您的回答,但它显示为黑色。 plt.savefig("test.pdf", use='pgf')
  • 以上链接中的代码使用ps,而我有多个34 figures。很难隐藏它们。
  • 有什么办法可以将它们全部转换成pdf。
  • 在 bash 终端中:for i in *.ps; do ps2pdf $i ; done
【解决方案2】:

tmdavison 的答案只支持ps 格式。所以,我试图解决接受任何格式的问题。为了展示我是如何解决这个问题的,我提供了一个数据集,让整个想法样本都能被理解。就我而言,我有超过 34 个不同点的图形,每个点都需要描述。我使用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2015-10-07
    • 1970-01-01
    • 2021-10-19
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多