Skip to main content
 首页 » 编程设计

python之如何在 Python 中为图形使用多种背景颜色

2025年04月02日16daizhj

我只想绘制几个数据集,比如 4,使用子图,即类似于

fig = figure(1) 
ax1 = fig.add_subplot(221) 
ax2 = fig.add_subplot(222) 
ax3 = fig.add_subplot(223) 
ax4 = fig.add_subplot(224) 

这很好用。但另外我想为第一行和第二行的两个子图设置不同的背景颜色,使得图形背景的上半部分为黑色,下半部分为白色。 谁能告诉我该怎么做?

好吧,到目前为止我尝试的是定义两个图形,一个是黑色的,另一个是白色背景的,将前两个子图添加到图 1 中,将其他子图添加到图 2 中。最后我合并了两个图转换为 PDF,但结果并不令人满意,因为 PDF 文件一团糟,而且这两个图形实际上看起来像两个不同的图形,但不像一个图形。

另外我试过类似的东西

fig = figure(1)  
rect = fig.patch 
rect.set_facecolor('black') 
ax1 = fig.add_subplot(221) 
ax2 = fig.add_subplot(222) 
rect = fig.patch 
rect.set_facecolor('white') 
ax3 = fig.add_subplot(223) 
ax4 = fig.add_subplot(224) 

但显然它不能像这样工作。然后我尝试使用 matplotlib.patches 为每个子图创建一个矩形作为背景,这似乎也不合适。

请您参考如下方法:

我遇到了同样的问题,想出了以下解决方案:

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
 
fig = plt.figure(1) 
 
# create rectangles for the background 
upper_bg = patches.Rectangle((0, 0.5), width=1, height=0.5,  
                             transform=fig.transFigure,      # use figure coordinates 
                             facecolor='gray',               # define color 
                             edgecolor='none',               # remove edges 
                             zorder=0)                       # send it to the background 
lower_bg = patches.Rectangle((0, 0), width=1.0, height=0.5,  
                             transform=fig.transFigure,      # use figure coordinates 
                             facecolor='white',              # define color 
                             edgecolor='none',               # remove edges 
                             zorder=0)                       # send it to the background 
 
# add rectangles to the figure 
fig.patches.extend([upper_bg, lower_bg]) 
 
# create subplots as usual 
fig.add_subplot(221) 
fig.add_subplot(222) 
fig.add_subplot(223) 
fig.add_subplot(224) 
 
plt.show() 

请注意,您必须显式设置 zorder,否则补丁将位于子图之前。结果图如下所示:

这种方法仍然依赖于 matplotlib.patches,因此可能不是您正在寻找的干净方法,但我认为它可能对遇到此问题的其他人有用。

可以在此处找到有关操纵图形本身的更多信息:http://matplotlib.org/users/artists.html#figure-container