matplotlib的表格图例布局 [英] tabular legend layout for matplotlib

查看:364
本文介绍了matplotlib的表格图例布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条9条线的图,代表具有两个不同参数的数据集,例如f_11,f_12,f_13,...,f_33.为了使图更加清晰,我将第一个参数编码为线条的颜色,将第二个参数编码为线条的样式(因此f_11为红色&虚线,f12为红色&虚线,f21为绿色&虚线,f22为绿色和点划线等).因此,对于图例,我想制作一个3x3的桌子,看起来像

I have a plot with 9 lines, representing datasets with two varying parameters, say f_11, f_12, f_13, ..., f_33. To make the plot (a bit) clearer, I encode the first parameter as the color of the line and the second one as the linestyle (so f_11 is red & dashed, f12 is red & dotted, f21 is green & dashed, f22 is green & dotted, etc.). So, for the legend, I would like to make a 3x3 table, looking like

       | value1 | value2 | value3
---------------------------------
value1 |
value2 |    <artists go there>
value3 |

有什么办法可以使用matplotlib做到这一点吗?一个想法是用LaTeX制作这个盒子,但是我需要一种在正确位置绘制图例艺术家的方法.

Is there any way I can make this with matplotlib? An idea would be to make this box with LaTeX, but I need a way to plot the legend artists at the right position.

谢谢!

(来自matplotlib用户)

(crosspossted from matplotlib-users)

推荐答案

这不是一个很简单的问题,但我知道了.我使用的技巧是初始化一个用作句柄的空矩形.这些额外的空句柄用于构造表.我使用handletextpad消除了多余的空间:

Not a very easy question but I figured it out. The trick I use is to initialize an empty rectangle which acts as a handle. These additional empty handles are used to construct the table. I get rid of any excessive space using handletextpad:

import numpy
import pylab
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig = plt.figure()
ax = fig.add_subplot(111)

im1 ,= ax.plot(range(10), pylab.randn(10), "r--")
im2 ,= ax.plot(range(10), pylab.randn(10), "g--")
im3 ,= ax.plot(range(10), pylab.randn(10), "b--")
im4 ,= ax.plot(range(10), pylab.randn(10), "r.")
im5 ,= ax.plot(range(10), pylab.randn(10), "g.")
im6 ,= ax.plot(range(10), pylab.randn(10), "b.")
im7 ,= ax.plot(range(10), pylab.randn(10), "r^")
im8 ,= ax.plot(range(10), pylab.randn(10), "g^")
im9 ,= ax.plot(range(10), pylab.randn(10), "b^")

# create blank rectangle
extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)

#Create organized list containing all handles for table. Extra represent empty space
legend_handle = [extra, extra, extra, extra, extra, im1, im2, im3, extra, im4, im5, im6, extra, im7, im8, im9]

#Define the labels
label_row_1 = [r"$f_{i,j}$", r"$i = 1$", r"$i = 2$", r"$i = 3$"]
label_j_1 = [r"$j = 1$"]
label_j_2 = [r"$j = 2$"]
label_j_3 = [r"$j = 3$"]
label_empty = [""]

#organize labels for table construction
legend_labels = numpy.concatenate([label_row_1, label_j_1, label_empty * 3, label_j_2, label_empty * 3, label_j_3, label_empty * 3])

#Create legend
ax.legend(legend_handle, legend_labels, 
          loc = 9, ncol = 4, shadow = True, handletextpad = -2)

plt.show()

这篇关于matplotlib的表格图例布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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