【问题标题】:How to use multiple background colors for a figure in Python?如何在 Python 中为图形使用多种背景颜色?
【发布时间】:2016-11-15 03:18:25
【问题描述】:

我只想绘制几个数据集,比如 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 为每个子图创建一个矩形作为背景,这似乎也不合适。

【问题讨论】:

  • 您能把到目前为止您尝试过的内容包括在内吗?
  • 据我所知,通过更改子图的背景颜色,我更改了绘图区域的颜色,但我想更改画布的颜色。

标签: python background-color figure subfigure


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多