如何更改绘图背景色?

2024-05-13 07:41:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

enter image description here

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


Tags: 方法绘图matplotlibfig绘制pltxkcdpatch
3条回答

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

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

enter image description here

一种方法是在脚本中手动设置轴背景色的默认值(请参见Customizing 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'

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

  • 您一起创建了一个图形和轴

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

然后您可以使用set_facecolor

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

example plot with pink background on the axes

作为什么颜色的提神剂:

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.

相关问题 更多 >