问题:如何更改情节背景颜色?

我正在matplotlib中制作散点图,需要将实际图的背景更改为黑色。我知道如何使用以下方法更改情节的脸色:

fig = plt.figure()
fig.patch.set_facecolor('xkcd:mint green')

在此处输入图片说明

我的问题是,这会改变情节周围空间的颜色。如何更改绘图的实际背景颜色?

I am making a scatter plot in matplotlib and need to change the background of the actual plot to black. I know how to change the face color of the plot using:

fig = plt.figure()
fig.patch.set_facecolor('xkcd:mint green')

enter image description here

My issue is that this changes the color of the space around the plot. How to I change the actual background color of the plot?


回答 0

使用对象set_facecolor(color)方法,axes方法是您通过以下方法之一创建的:

  • 您一起创建了图形和轴

    fig, ax = plt.subplots(nrows=1, ncols=1)
  • 您创建了一个图形,然后再创建一个轴

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
    
  • 您使用了有状态的API(如果您要做的事情不止几行,尤其是如果您有多个绘图,则上述面向对象的方法可以简化工作,因为您可以引用特定的图形,在某些轴上进行绘图并自定义要么)

    plt.plot(...)
    ax = plt.gca()
    

然后,您可以使用set_facecolor

ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))

轴上带有粉红色背景的示例图

作为颜色的复习:

matplotlib.colors

Matplotlib可识别以下格式以指定颜色:

  • 浮动值的RGB或RGBA元组[0, 1](例如(0.1, 0.2, 0.5)(0.1, 0.2, 0.5, 0.3));
  • 十六进制RGB或RGBA字符串(例如'#0F0F0F''#0F0F0F0F');
  • 浮点值的字符串表示形式,[0, 1]包括灰度值(例如'0.5');
  • 之一{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'};
  • X11 / CSS4颜色名称;
  • 来自xkcd颜色调查的名字; 前缀'xkcd:'(例如'xkcd:sky blue');
  • 其中之一{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}是“ T10”分类调色板中的Tableau颜色(这是默认颜色周期);
  • “ CN”颜色规范,即“ C”后跟一位数字,这是默认属性周期(matplotlib.rcParams['axes.prop_cycle'])的索引;该索引在艺术家创建时发生,如果循环不包含颜色,则默认为黑色。

除“ CN”外,所有颜色的字符串规格均不区分大小写。

Use the set_facecolor(color) method of the axes object, which you’ve created one of the following ways:

  • You created a figure and axis/es together

    fig, ax = plt.subplots(nrows=1, ncols=1)
    
  • You created a figure, then axis/es later

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
    
  • You used the stateful API (if you’re doing anything more than a few lines, and especially if you have multiple plots, the object-oriented methods above make life easier because you can refer to specific figures, plot on certain axes, and customize either)

    plt.plot(...)
    ax = plt.gca()
    

Then you can use set_facecolor:

ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))

example plot with pink background on the axes

As a refresher for what colors can be:

matplotlib.colors

Matplotlib recognizes the following formats to specify a color:

  • an RGB or RGBA tuple of float values in [0, 1] (e.g., (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3));
  • a hex RGB or RGBA string (e.g., '#0F0F0F' or '#0F0F0F0F');
  • a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5');
  • one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'};
  • a X11/CSS4 color name;
  • a name from the xkcd color survey; prefixed with 'xkcd:' (e.g., 'xkcd:sky blue');
  • one of {'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'} which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle);
  • a “CN” color spec, i.e. ‘C’ followed by a single digit, which is an index into the default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.

All string specifications of color, other than “CN”, are case-insensitive.


回答 1

一种方法是在脚本中手动设置轴背景色的默认值(请参阅自定义matplotlib):

import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'

这与Nick T的方法相反,后者更改了特定axes对象的背景颜色。如果您要制作多个具有相似样式的不同绘图,并且不想不断更改其他axes对象,则重置默认值很有用。

注意:相当于

fig = plt.figure()
fig.patch.set_facecolor('black')

从您的问题是:

plt.rcParams['figure.facecolor'] = 'black'

One method is to manually set the default for the axis background color within your script (see Customizing matplotlib):

import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'

This is in contrast to Nick T’s method which changes the background color for a specific axes object. Resetting the defaults is useful if you’re making multiple different plots with similar styles and don’t want to keep changing different axes objects.

Note: The equivalent for

fig = plt.figure()
fig.patch.set_facecolor('black')

from your question is:

plt.rcParams['figure.facecolor'] = 'black'

回答 2

像这样吗 使用axisbg关键字subplot

>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')

(授予的,不是散点图,也不是黑色背景。)

在此处输入图片说明

Something like this? Use the axisbg keyword to subplot:

>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')

(Granted, not a scatter plot, and not a black background.)

enter image description here


回答 3

如果您已经有了axes对象,就像Nick T的答案一样,您也可以使用

 ax.patch.set_facecolor('black')

If you already have axes object, just like in Nick T‘s answer, you can also use

 ax.patch.set_facecolor('black')

回答 4

其他答案中的一个建议是使用ax.set_axis_bgcolor("red")。但是,此方法已被弃用,并且不适用于MatPlotLib> = v2.0。

还有建议使用ax.patch.set_facecolor("red")(在MatPlotLib v1.5和v2.2上均可使用)。虽然这很好用,但对于v2.0 +来说,更简单的解决方案是使用

ax.set_facecolor("red")

One suggestion in other answers is to use ax.set_axis_bgcolor("red"). This however is deprecated, and doesn’t work on MatPlotLib >= v2.0.

There is also the suggestion to use ax.patch.set_facecolor("red") (works on both MatPlotLib v1.5 & v2.2). While this works fine, an even easier solution for v2.0+ is to use

ax.set_facecolor("red")


回答 5

最简单的方法可能是在创建绘图时提供颜色:

fig1 = plt.figure(facecolor=(1, 1, 1))

要么

fig1, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, facecolor=(1, 1, 1))

The easiest thing is probably to provide the color when you create the plot :

fig1 = plt.figure(facecolor=(1, 1, 1))

or

fig1, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, facecolor=(1, 1, 1))

回答 6

比较简单的答案:

ax = plt.axes()
ax.set_facecolor('silver')

simpler answer:

ax = plt.axes()
ax.set_facecolor('silver')

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。