Python:为子图的每一行绘制不同的图形背景颜色 [英] Python: Plot Different Figure Background Color For Each Row of Subplots

查看:81
本文介绍了Python:为子图的每一行绘制不同的图形背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个9 sibplots的图形(3行x 3列).我想以每行不同的颜色绘制图的背景颜色(而不是子图!).这是我到目前为止的内容:

I have a figure of 9 sibplots (3 rows x 3 columns). I would like to plot the background color of the figure (not the subplots!) in a different color for each row. This is what I have so far:

# Imports
import matplotlib.pyplot as plt
import numpy as np

# Plot the Figure

fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(9, 9))

for r in np.arange(3):
    for c in np.arange(3):
        axes[r, c].plot(np.arange(10), np.random.randint(10, size=10))
        if r == 0:
            axes[r, c].patch.set_facecolor('azure')
        if r == 1:
            axes[r, c].patch.set_facecolor('hotpink')
        if r == 2:
            axes[r, c].patch.set_facecolor('lightyellow')
plt.show()

该图是错误的,因为它会为每个子图的背景上色.但是我要为每一行的图形背景(子图外)着色不同.我该怎么办?

This figure is wrong in the sense that it colors the background inside each subplot. But what I want is to color the figure background (outside the subplots) differently for each row. How can I do this?

推荐答案

类似的东西?

fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(9, 9))

for r in np.arange(3):
    for c in np.arange(3):
        axes[r, c].plot(np.arange(10), np.random.randint(10, size=10))

colors = ['azure','hotpink','lightyellow']
for ax,color in zip(axes[:,0],colors):
    bbox = ax.get_position()
    rect = matplotlib.patches.Rectangle((0,bbox.y0),1,bbox.height, color=color, zorder=-1)
    fig.add_artist(rect)
plt.show()

matplotlib的代码.__version __< 3.0

以下代码在不存在 Figure.add_artist()的较旧版本的matplotlib中工作.但是,我发现在其中一个轴上添加矩形会导致该轴背景色块出现问题,因此我不得不隐藏所有背景以保持一致的外观.

The following code works in older version of matplotlib where Figure.add_artist() does not exist. However, I found that adding the rectangle to one of the axes causes problem for that axes background patch, so I had to hide all the backgrounds for a consistent look.

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

fig, axes = plt.subplots(nrows=3, ncols=3)

for r in np.arange(3):
    for c in np.arange(3):
        axes[r, c].plot(np.arange(10), np.random.randint(10, size=10))

fig.tight_layout()

colors = ['azure','hotpink','lightyellow']
for ax,color in zip(axes[:,0],colors):
    bbox = ax.get_position()
    rect = Rectangle((0,bbox.y0),1,bbox.height, color=color, zorder=-1, transform=fig.transFigure, clip_on=False)
    ax.add_artist(rect)
for ax in axes.flat:
    ax.patch.set_visible(False)
plt.show()

这篇关于Python:为子图的每一行绘制不同的图形背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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