Python 如何更改绘图背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14088687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:24:59  来源:igfitidea点击:

How to change plot background color?

pythonmatplotlib

提问by user1764386

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:

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

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?

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

回答by user1764386

Something like this? Use the axisbgkeyword to subplot:

像这样的东西?使用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')

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

(当然,不是散点图,也不是黑色背景。)

enter image description here

在此处输入图片说明

回答by Nick T

Use the set_facecolor(color)method of the axesobject, which you've created one of the following ways:

使用objectset_facecolor(color)方法axes,您已经通过以下方式之一创建了该方法:

  • 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 especiallyif 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()
    
  • 您一起创建了一个图形和轴

    fig, ax = plt.subplots(nrows=1, ncols=1)
    
  • 您创建了一个图形,然后是axis/es

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
    
  • 您使用了有状态 API(如果您要做的不仅仅是几行,特别是如果您有多个绘图,上面的面向对象方法会让生活更轻松,因为您可以参考特定图形、在某些轴上绘图并自定义任何一个)

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

Then you can use set_facecolor:

然后你可以使用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.

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”之外的所有颜色字符串规范都不区分大小写。

回答by Mathias711

If you already have axesobject, just like in Nick T's answer, you can also use

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

 ax.patch.set_facecolor('black')

回答by BurlyPaulson

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

一种方法是在脚本中手动设置轴背景颜色的默认值(请参阅自定义 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 axesobject. Resetting the defaults is useful if you're making multiple different plots with similar styles and don't want to keep changing different axesobjects.

这与 Nick T 的方法形成对比,后者更改特定axes对象的背景颜色。如果您正在制作具有相似样式的多个不同绘图并且不想不断更改不同的axes对象,则重置默认值非常有用。

Note: The equivalent for

注意:相当于

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

from your question is:

从你的问题是:

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

回答by ImportanceOfBeingErnest

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.

其他答案中的一个建议是使用ax.set_axis_bgcolor("red"). 然而,这已被弃用,并且不适用于 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.patch.set_facecolor("red")(适用于 MatPlotLib v1.5 和 v2.2)。虽然这工作正常,但 v2.0+ 的一个更简单的解决方案是使用

ax.set_facecolor("red")

ax.set_facecolor("red")

回答by Flonks

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))

回答by Leigh

simpler answer:

更简单的答案:

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