如何避免Seaborn干扰Matplotlib绘图?已试多种方案均无效
问题描述
- 先使用Matplotlib绘制图表,再用Seaborn绘图后,所有后续Matplotlib图表颜色被更改;重新运行Seaborn所在单元格,之前的Matplotlib图表颜色也会发生变化
- 已尝试但无效的解决方法:
- 在笔记本开头执行
plt.style.use('default') - 在Seaborn代码单元格的开头/结尾调用
sns.reset_orig()重置RC参数 - 尝试导入
seaborn.apionly(该模块已不存在) - 执行
plt.rcParams['axes.prop_cycle'] = plt.rcParamsDefault['axes.prop_cycle']重置颜色循环
- 在笔记本开头执行
问题代码
# When you import seaborn the default styling is changed. import seaborn as sns ## Reset Seaborn to default Matplotlib settings sns.reset_orig() # transform the numpy array into panda data frame df = pd.DataFrame(data_T) # Replace the name of the column with labels defines above df.columns = labels # Create pairplot with only the lower triangular part g = sns.set(style="ticks") g = sns.pairplot(df, corner=True, diag_kind='hist', plot_kws = dict(marker="+", linewidth=1), vars = labels, # labels hue = "pwv [mm]") # variable in 3rd dimension # , palette = colors) # varslist of variable names # remove the 3rd dimension in the histogram g.map_diag(sns.histplot, hue=None, color = '0.4') plt.savefig('triqngle_plot02.png')
解决方案
核心问题是你调用了sns.set(style="ticks")——这个方法会永久覆盖Matplotlib的全局RC参数,哪怕之前调用了sns.reset_orig()也无法阻止。以下是两种可行的解决思路:
方法1:用上下文管理器隔离Seaborn样式
不全局设置Seaborn样式,仅在绘制Seaborn图表时临时应用样式,不影响全局Matplotlib配置:
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt # 转换数据为DataFrame df = pd.DataFrame(data_T) df.columns = labels # 仅在上下文内应用Seaborn的ticks样式 with sns.axes_style("ticks"): g = sns.pairplot(df, corner=True, diag_kind='hist', plot_kws = dict(marker="+", linewidth=1), vars = labels, hue = "pwv [mm]") g.map_diag(sns.histplot, hue=None, color = '0.4') plt.savefig('triqngle_plot02.png') plt.close() # 关闭当前画布,避免样式残留
方法2:彻底重置Matplotlib到默认状态
如果必须使用sns.set(),就在绘制完成后完全恢复Matplotlib的默认参数:
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt # 先保存Matplotlib的默认RC参数 default_rc_params = plt.rcParamsDefault.copy() # 绘制Seaborn图表 df = pd.DataFrame(data_T) df.columns = labels g = sns.set(style="ticks") g = sns.pairplot(df, corner=True, diag_kind='hist', plot_kws = dict(marker="+", linewidth=1), vars = labels, hue = "pwv [mm]") g.map_diag(sns.histplot, hue=None, color = '0.4') plt.savefig('triqngle_plot02.png') plt.close() # 强制恢复到Matplotlib默认参数 plt.rcParams.update(default_rc_params)
关键注意事项
- 避免全局调用
sns.set():该方法会永久修改Matplotlib全局样式,sns.reset_orig()仅能重置到Seaborn导入前的状态,无法覆盖后续sns.set()的修改 - 绘制后关闭画布:调用
plt.close()可以避免Seaborn绘图的样式残留到后续Matplotlib图表中 - 明确指定颜色:如果使用Matplotlib的缩写色(如
b/m),可以改为全称(如blue/magenta),彻底避免样式映射带来的干扰
内容的提问来源于stack exchange,提问作者Apinorr
相关产品推荐
相关产品推荐

