首页 > 解决方案 > 没有框架的 Matplotlib 子图面颜色

问题描述

当我使用 matplotlib 时,我想控制(子)图的表面颜色。

例如,如果我跑步,

tips = sns.load_dataset("tips")
f, ax = plt.subplots(subplot_kw=dict(facecolor=".9"))
sns.scatterplot(data=tips, x="total_bill", y="tip")

我明白了,

在此处输入图像描述

默认的白色面部颜色更改为灰色。虽然跑步,

tips = sns.load_dataset("tips")
rows, cols = 1, 1
f, axs = plt.subplots( rows, cols, subplot_kw=dict(facecolor=".9"))
plt.subplot( rows, cols, 1)
sns.scatterplot(data=tips, x="total_bill", y="tip")

给,

在此处输入图像描述

在每个子图命令中明确设置面颜色可以解决它,即

tips = sns.load_dataset("tips")
rows, cols = 1, 1
f, axs = plt.subplots( rows, cols)
plt.subplot( rows, cols, 1, facecolor=".9")
sns.scatterplot(data=tips, x="total_bill", y="tip")

在此处输入图像描述

但是,当我使用plt.box( False)

ax = plt.subplot( rows, cols, 1, facecolor = ".9")
ax.set_frame_on( False)

或者

plt.subplot( rows, cols, 1, facecolor = ".9", frame_on = False)

问题又回来了。看来,没有框架的自定义面部颜色不能作为“配置”来满足。

frame_on属性的文档中,“设置是否绘制轴矩形补丁。”,https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_frame_on.html#matplotlib.axes.Axes.set_frame_on。因此,它看起来像matplotlib添加了一个补丁来改变面部颜色。

那么是否可以更改此补丁的边缘颜色?我不想有这个“厚”的框架边框线。添加我自己的补丁是唯一的选择吗?

编辑

当我尝试这个时,

tips = sns.load_dataset("tips")
rows, cols = 2, 1
f, axs = plt.subplots( rows, cols, figsize = ( 10, 10), subplot_kw = dict( facecolor = ".9"))
plt.subplot( rows, cols, 1)
sns.scatterplot(data=tips, x="total_bill", y="tip", ax = axs[ 0])
axs[ 0].grid( color = 'w', linewidth = 1)
[ axs[ 0].spines[ s].set_visible( False) for s in axs[ 0].spines.keys()]

我明白了,

在此处输入图像描述

问题是我正在调用plt.subplot()创建一个新轴来覆盖位置的轴( rows, cols, 1)。删除此行即可解决问题。

谢谢。

标签: pythonmatplotlibseabornsubplot

解决方案


您可以使用set_visible以下方法spines

tips = sns.load_dataset("tips")
rows, cols = 1, 1
f, axs = plt.subplots( rows, cols)
ax = plt.subplot( rows, cols, 1, facecolor=".9")
for s in ax.spines:
  ax.spines[s].set_visible(False)

sns.scatterplot(data=tips, x="total_bill", y="tip")

在此处输入图像描述


推荐阅读