You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Matplotlib绘图边框颜色从深灰色改为白色?

解决Matplotlib绘图边框颜色改为白色的问题

你遇到的问题主要有两个:一是修改facecolor无效是因为你在绘图后创建了新的空白图,而非修改已有绘图的图;二是要把边框(轴脊)改成白色,需要单独设置轴脊的颜色。

修正后的代码

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('classic')
from mpl_toolkits.axes_grid1 import make_axes_locatable

def plot_hist(*argv, titles):
    """
    plots the historgram of the input phase maps
    """
    # 先创建指定背景色的图,并获取轴对象
    fig = plt.figure(facecolor='white')
    ax = plt.gca()
    
    for i in range(len(argv)):
        hist = np.histogram(argv[i].ravel(), bins=100)
        ax.plot(hist[1][1:], hist[0])
    
    # 设置轴标签和标题
    ax.set_xlabel("phase values")
    ax.set_ylabel("frequency")
    ax.set_title("Histogram Analysis")
    ax.grid()
    
    if titles is not None:
        ax.legend(titles)
    
    # 将所有轴脊(边框)颜色改为白色
    for spine in ax.spines.values():
        spine.set_color('white')
    
    # 可选:如果需要让刻度文字也变成白色(适配深色背景)
    ax.tick_params(axis='both', colors='white')
    
    plt.show()

关键修改说明

  • 修正背景色设置:你之前的fig=plt.figure(facecolor='white')是在绘图后执行的,这会创建一个新的空白图,对已经绘制好的图没有影响。现在我们在绘图前就创建指定背景色的图,确保生效。
  • 修改轴脊(边框)颜色:Matplotlib中绘图的边框是轴对象的spines(轴脊),通过遍历所有轴脊并设置set_color('white'),就能把边框改成白色。
  • 可选:刻度颜色调整:如果你的图背景是深色,白色边框搭配白色刻度会更协调,所以添加了ax.tick_params来修改刻度颜色,不需要可以删除这一行。

内容的提问来源于stack exchange,提问作者Awais

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:42:42