python - 如何更改绘图背景颜色?

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

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

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

最佳答案

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

  • 您一起创建了图形和轴

    fig, ax = plt.subplots(nrows=1, ncols=1)
    
  • 你创建了一个图形,然后是轴/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))

作为复习可以是什么颜色:

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.

https://stackoverflow.com/questions/14088687/

相关文章:

python - 在 Python 2.6 中不推荐使用 BaseException.message

python - 将字符串转换为 Python 类对象?

linux - 在 bash 中检查当前分区的可用磁盘空间

linux - 创建 .tar.gz 文件时排除目录

python - 如何让 Flask 在端口 80 上运行?

linux - 从 linux shell 脚本发送邮件

linux - ~/.ssh/config 文件中的 SSH 端口转发?

python - 无法安装 Python 包 [SSL : TLSV1_ALERT_PROTOCOL

python - 无法使用 Ctrl-C 终止 Python 脚本

python - 通过urllib和python下载图片