pyplot:更改图例中的ncol [英] pyplot: change ncols within a legend

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

问题描述

我正在 pyplot 中绘制一个大型数据集和一些回归.数据根据附加值着色.我决定将图例中的列数设置为2.

I'm plotting a large data set and some regressions in pyplot. The data is colored according to an additional value. I decided to set the number of columns in the legend to 2.

对于数据点来说看起来不错,但是对于回归,我想回到ncols = 1.可以在一个图例中做到这一点吗?

It looks nice for the data points, but for the regressions, I'd like to go back to ncols=1. It is possible to do this within one legend?

(我知道,我可以声明两个传说,但我想避免这种情况...)

(I know, I could declare two legends but I'd like to avoid this...)

推荐答案

matplotlib 中的图例是 OffsetBox 的集合.原则上,可以通过手动重新排列这些偏移框来更改图例中的"ncol".当然,这需要一些 matplotlib 内部知识,对于普通用户来说会很困难.不确定什么是揭露这一点的最佳方式.这是一个简单的代码,可以创建两个图例并将它们组合成一个图例.

Legend in matplotlib is a collection of OffsetBox. In principle, you can change "ncol" within a legend by manually rearranging these offsetboxes. Of course, this needs some knowledge of matplotlib internals and will be difficult for normal users. Not sure what would be the best way to expose this. Here is a simple code that creates two legends and combine them into one.

import matplotlib.pyplot as plt
import matplotlib.legend as mlegend

ax = plt.subplot(111)
l1, = ax.plot([1,2,3])

leg1 = ax.legend([l1], ["long lable"], ncol=1)

leg2 = mlegend.Legend(ax, [l1, l1, l1, l1], tuple("1234"), ncol=2)

leg1._legend_box._children.append(leg2._legend_box._children[1])
leg1._legend_box.align="left" # the default layout is 'center'

plt.show()

这篇关于pyplot:更改图例中的ncol的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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