程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

matplotlib的子图中的行和列标题

发布于2019-08-24 15:01     阅读(1390)     评论(0)     点赞(17)     收藏(2)


将行和列标题添加到循环中生成的子图网格中的最佳做法是matplotlib什么?我能想到一对,但不是特别整洁:

  1. 对于列,使用循环计数器,您只能使用set_title()第一行。对于行,这不起作用。你必须text在地块之外画画
  2. 您在顶部添加了一行额外的子图,在左侧添加了一列额外的子图,并在该子图的中间绘制文本。

你能建议一个更好的选择吗?

在此输入图像描述


解决方案


有几种方法可以做到这一点。简单的方法是利用图表的y标签和标题,然后用来fig.tight_layout()为标签腾出空间。或者,您可以将其他文本放在正确的位置,annotate然后半手动为其腾出空间。


如果您的轴上没有y标签,则可以轻松利用第一行和第一列轴的标题和y标签。

import matplotlib.pyplot as plt

cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))

for ax, col in zip(axes[0], cols):
    ax.set_title(col)

for ax, row in zip(axes[:,0], rows):
    ax.set_ylabel(row, rotation=0, size='large')

fig.tight_layout()
plt.show()

在此输入图像描述


如果您有y标签,或者您更喜欢灵活性,则可以使用annotate标签。这更复杂,但除了行和列标签之外,还允许您拥有单独的绘图标题,ylabels等。

import matplotlib.pyplot as plt
from matplotlib.transforms import offset_copy


cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))
plt.setp(axes.flat, xlabel='X-label', ylabel='Y-label')

pad = 5 # in points

for ax, col in zip(axes[0], cols):
    ax.annotate(col, xy=(0.5, 1), xytext=(0, pad),
                xycoords='axes fraction', textcoords='offset points',
                size='large', ha='center', va='baseline')

for ax, row in zip(axes[:,0], rows):
    ax.annotate(row, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0),
                xycoords=ax.yaxis.label, textcoords='offset points',
                size='large', ha='right', va='center')

fig.tight_layout()
# tight_layout doesn't take these labels into account. We'll need 
# to make some room. These numbers are are manually tweaked. 
# You could automatically calculate them, but it's a pain.
fig.subplots_adjust(left=0.15, top=0.95)

plt.show()

在此输入图像描述



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/57089/331ccb0a26db5aaa6a74/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

17 0
收藏该文
已收藏

评论内容:(最多支持255个字符)