【问题标题】:Draw box around Seaborn FacetGrid axes围绕 Seaborn FacetGrid 轴绘制框
【发布时间】:2019-02-22 21:31:00
【问题描述】:

我无法弄清楚如何在每个构面网格元素周围绘制一个黑色边界框。

import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "time")
g.map(plt.hist, "tip")
plt.show()

给:

我想要这样的东西:

我尝试过使用

sb.reset_orig() #after the seaborn import, to reset to matplotlib original rc

以及轴本身的各种选项:

axes=g.axes.flatten()
for ax in axes:
    ax. # I can't figure out the right option.

这可能吗?

【问题讨论】:

  • 例如:for ax in axes: ax.spines['bottom'].set_color('black') ax.spines['top'].set_color('black') ax.spines['right'].set_color('black') ax.spines['left'].set_color('black') 仅将 X 轴和 Y 轴设为黑色 - 而不是右侧和顶部。嗯..

标签: pandas matplotlib plot seaborn


【解决方案1】:

我不确定为什么默认情况下刺不是set_visible,但我能够根据this 答案创建此解决方案。此外,我使用您的代码只得到两个子图,而不是问题中的 4 个子图。也许这是一个seaborn 问题。我通过循环 4 个刺使您的代码简洁。

import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
sb.set()

df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "time")
g.map(plt.hist, "tip")

for ax in g.axes.flatten(): # Loop directly on the flattened axes 
    for _, spine in ax.spines.items():
        spine.set_visible(True) # You have to first turn them on
        spine.set_color('black')
        spine.set_linewidth(4)

编辑(基于下面的 cmets)

在上面的答案中,由于您只想更改 ax.spines 字典中的刺(值)的属性,您也可以直接使用迭代值(刺)

for spine in ax.spines.values():

【讨论】:

  • 哇! @Bazingaa,太棒了 - 确实是 bazinga。我之前没见过for _, spine in ax.spines.items(): - 你能进一步解释一下,还是提供一个链接让我可以了解更多信息?谢谢!
  • 这里ax.spines 是一本字典。字典有键和值。要从字典中访问键值对,可以使用.items(),它返回一个(键,值)对。现在这些值是脊椎。由于您只想修改脊椎(值)的属性(属性),因此您使用for _, spine in ax.spines.items() 仅存储脊椎(值)。由于您不需要对密钥执行任何操作,因此请使用下划线 _,因为此处的密钥是多余的。检查我在答案中的编辑
【解决方案2】:

在已经提供的完整答案的基础上,还有一个快捷方式选项,在代码行中使用 despine=False 来启动构面网格。也就是说,您需要将 seaborn 情节的样式更改为 ticks

import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
sb.set(style='ticks')

df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "time", despine=False)
g.map(plt.hist, "tip");

图表如下:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 2016-11-09
    • 2019-08-02
    • 2017-12-20
    • 2014-09-12
    • 2020-09-26
    • 2018-12-09
    • 2014-10-31
    相关资源
    最近更新 更多