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

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

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


当前回答

简单的回答是:

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

其他回答

除了NickT的答案,你还可以通过设置为“none”来删除背景帧,如下所述:https://stackoverflow.com/a/67126649/8669161

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

最简单的事情可能是在创建图形时提供颜色:

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

or

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

像这样的东西?使用axisbg关键字绘制子图:

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

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

使用axis对象的set_facecolor(color)方法,你已经创建了以下方法之一:

您一起创建了图形和轴/es 图,ax = plt。次要情节(nrows = 1, ncols = 1) 您创建了一个图形,然后是轴/es 图= 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 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.

如果你已经有坐标轴对象了,就像尼克T的答案一样,你也可以用

 ax.patch.set_facecolor('black')