首页 > 解决方案 > 如何在seaborn中有一个带有暗网格背景的透明图形?

问题描述

保存透明图像时的默认行为是将背景设置为透明,但我希望背景保持原样,并且图中绘图周围的空白区域是透明的。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

%load_ext autoreload
%autoreload 2
%matplotlib inline
%config InlineBackend.figure_format = 'svg'

tips = sns.load_dataset("tips")

# Set background of the charts' to be a dark grid.
sns.set_style("darkgrid")

g = sns.FacetGrid(tips, col="smoker", col_order=["Yes", "No"])
g = g.map(plt.hist, "total_bill")

# Save figure with a transparent background (but this unfortunately)
# overrides the dark grid, whereas I want the white surrounding the
# plots to be transparent.
plt.savefig("example.pdf", transparent=True)

如图笔记本所示(带darkgrid) 如图笔记本所示(带有暗格)。

看起来已保存的图(无背景) 看起来已保存的图(无背景)

标签: matplotlibseaborn

解决方案


您可以更新matplotlib'srcParams以使图形背景透明但保持网格处于活动状态,将其添加到您的代码中:

from matplotlib import rc

matplotlib.rcParams['axes.grid'] = True
matplotlib.rcParams['savefig.transparent'] = True

推荐阅读