Python Matplotlib多色图例条目 [英] Python Matplotlib Multi-color Legend Entry

查看:76
本文介绍了Python Matplotlib多色图例条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使matplotlib中的图例条目看起来像这样:

I would like to make a legend entry in a matplotlib look something like this:

给定的图例项有多种颜色.下面显示的代码将输出一个红色矩形.我想知道我需要怎么做才能将一种颜色覆盖在另一种颜色之上?还是有更好的解决方案?

It has multiple colors for a given legend item. Code is shown below which outputs a red rectangle. I'm wondering what I need to do to overlay one color ontop of another? Or is there a better solution?

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='Foo')
plt.legend(handles=[red_patch])

plt.show()

推荐答案

我提出的解决方案是将两个不同的代理艺术家,用于此处的输入图例,如下所述:

The solution I am proposing is to combine two different proxy-artists for one entry legend, as described here: Combine two Pyplot patches for legend.

然后的策略是将第一个方形标记的fillstyle设置为left,而另一个将其设置为right(请参见

The strategy is then to set the fillstyle of the first square marker to left while the other one is set to right (see http://matplotlib.org/1.3.0/examples/pylab_examples/filledmarker_demo.html). Two different colours can then be attributed to each marker in order to produce the desired two-colour legend entry.

下面的代码显示了如何完成此操作.请注意,plt.legend中的numpoints=1参数对于每个条目仅显示一个标记很重要.

The code below show how this can be done. Note that the numpoints=1 argument in plt.legend is important in order to display only one marker for each entry.

import matplotlib.pyplot as plt

plt.close('all')

#---- Generate a Figure ----

fig = plt.figure(figsize=(4, 4))
ax = fig.add_axes([0.15, 0.15, 0.75, 0.75])
ax.axis([0, 1, 0, 1])

#---- Define First Legend Entry ----

m1, = ax.plot([], [], c='red' , marker='s', markersize=20,
              fillstyle='left', linestyle='none')

m2, = ax.plot([], [], c='blue' , marker='s', markersize=20,
              fillstyle='right', linestyle='none')

#---- Define Second Legend Entry ----

m3, = ax.plot([], [], c='cyan' , marker='s', markersize=20,
              fillstyle='left', linestyle='none')

m4, = ax.plot([], [], c='magenta' , marker='s', markersize=20,
              fillstyle='right', linestyle='none')

#---- Plot Legend ----

ax.legend(((m2, m1), (m3, m4)), ('Foo', 'Foo2'), numpoints=1, labelspacing=2,
          loc='center', fontsize=16)

plt.show(block=False)

这将导致:

免责声明::这仅适用于两色图例条目.如果需要两种以上的颜色,除了@jwinterm(

Disclaimer: This will only work for a two-colors legend entry. If more than two colours is desired, I cannot think of any other way to do this other than the approach described by @jwinterm (Python Matplotlib Multi-color Legend Entry)

这篇关于Python Matplotlib多色图例条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆