Python - 不使用ax.text的颜色编码标签?

时间:2017-03-03 19:38:29

标签: python matplotlib text plot

虽然使用matplotlib的图例模块可以区别地标记我的图,但我想使用颜色标记(没有线条)来标记我的图:

enter image description here

如果我在我的情节中去哪里,我会使用text模块放入相同颜色的标签。例如,从我的情节:

fig6 = plt.figure()
VelCumullog = fig6.add_subplot(111)


VelCumullog.plot(VelCumu[0], VelCumu[1], color = 'slateblue', label = 'Illustris-1')
VelCumullog.plot(VelCumuD[0], VelCumuD[1], color = 'crimson',  label = 'Illustris-1-Dark')
VelCumullog.set_xscale('log')
VelCumullog.set_yscale('log')
VelCumullog.set_xlim(50,500)
VelCumullog.set_ylim(1,5000)
VelCumullog.set_xlabel('$\mathrm{Velocity\ Relative\ to\ Host}\ [\mathrm{km}\ \mathrm{s}^{-1}]$')
VelCumullog.set_ylabel('$N\ (>v_{\mathrm{rel}})$ ', labelpad=-1)
VelCumullog.set_xticks([100, 1000])
VelCumullog.set_yticks([10, 100, 1000])
VelCumullog.get_xaxis().set_major_formatter(tic.ScalarFormatter())
VelCumullog.get_yaxis().set_major_formatter(tic.ScalarFormatter())
#VelCumullog.legend(loc='upper left', frameon=False)
VelCumullog.text(60, 2800, 'Illustris-1', color='slateblue')
VelCumullog.text(60, 1800, 'Illustris-1-Dark', color='crimson')

enter image description here

你看到我的地方只使用text而不是传说。

但是正如你所看到的,如果我在其他地块上使用这种方法,那么将标签放置在绘图上会非常繁琐,因为我必须定义它们的坐标。特别是如果与图中的其他文本相比,文本之间的间距是关闭的。

我想知道他们是否会成为我想要做的另一种方法,例如使用legends模块,或其他让我的生活更轻松的方法。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你希望你的传说没有线条,并且文字是彩色的。我们可以在调用图例时设置handlelength=0并手动更改文本颜色。

以下适用于我:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import matplotlib.ticker as tic
fig6 = plt.figure()
VelCumullog = fig6.add_subplot(111)

VelCumu = [np.arange(0,1000,1.0)]
VelCumu.append(1000-2.0*VelCumu[0])
VelCumuD = [np.arange(0,1000,1.0)]
VelCumuD.append(1200-2.0*VelCumu[0])

VelCumullog.plot(VelCumu[0], VelCumu[1], color = 'slateblue', label = 'Illustris-1')
VelCumullog.plot(VelCumuD[0], VelCumuD[1], color = 'crimson',  label = 'Illustris-1-Dark')
VelCumullog.set_xscale('log')
VelCumullog.set_yscale('log')
VelCumullog.set_xlim(50,500)
VelCumullog.set_ylim(1,5000)
VelCumullog.set_xlabel('$\mathrm{Velocity\ Relative\ to\ Host}\ [\mathrm{km}\ \mathrm{s}^{-1}]$')
VelCumullog.set_ylabel('$N\ (>v_{\mathrm{rel}})$ ', labelpad=-1)
VelCumullog.set_xticks([100, 1000])
VelCumullog.set_yticks([10, 100, 1000])
VelCumullog.get_xaxis().set_major_formatter(tic.ScalarFormatter())
VelCumullog.get_yaxis().set_major_formatter(tic.ScalarFormatter())
l = VelCumullog.legend(loc='upper left', frameon=False, handlelength=0)
l.get_texts()[0].set_color('slateblue')
l.get_texts()[1].set_color('crimson')

plt.show()

enter image description here

如果这不起作用,您可以尝试将绘制图例图形的Artist更改为隐藏框:

empty = Rectangle((0, 0), 0, 0, alpha=0.0)
l = VelCumullog.legend([empty, empty], ['Illustris-1', 'Illustris-1-Dark'], loc='upper left', frameon=False, handlelength=0, handletextpad=0)
l.get_texts()[0].set_color('slateblue')
l.get_texts()[1].set_color('crimson')

注意我还设置handletextpad=0这可能有助于解决某些对齐问题(删除不可见的艺术家和标签之间的空格)。