【问题标题】:Seaborn set figsize=(x,y) error and warning about tight_layout "tight_layout cannot make axes height small enough to accommodate all axes decorations"Seaborn 设置 figsize=(x,y) 错误和关于紧密布局的警告“紧密布局不能使轴高度小到足以容纳所有轴装饰”
【发布时间】:2019-06-16 19:55:15
【问题描述】:

我在 Seaborn 中有一个包含 10 个图的 FacetGrid 图表,其中的图略有重叠。我想改变整体图的大小。当我在下面的代码中使用 g.fig.subplots(figsize=(12,12)) 时,我收到一条错误消息TypeError: subplots() got an unexpected keyword argument 'size'

另外,我收到关于 UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations self.fig.tight_layout() 的警告

我在我的代码中没有看到引用了 tight_layout() 的任何地方。它嵌入在模块中:C:\Anaconda3\lib\site-packages\seaborn\axisgrid.py:848。我不想在站点包模块中乱七八糟。如何调整参数以免收到此警告。

我想解决这个问题,而不仅仅是取消这个警告。我对 Seaborn 和 Matplotlib 的内部了解不够,无法修复此错误并消除警告。

我尝试添加g.fig.subplots(figsize=(12,12)) 来更改图形大小。显然 FacetGrid 图不包含在图形中,或者我错误地引用了图形边界框对象。

"""
FacetGrid Plot Showing Overlapping Distributions (Densities) Offset by ('ridge plot')
====================================
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})

# Create some random distribution data and labels, and store them in a dataframe
rs = np.random.RandomState(1979)
x = rs.randn(500)
g = np.tile(list("ABCDEFGHIJ"), 50)
df = pd.DataFrame(dict(x=x, g=g))
m = df.g.map(ord)
df["x"] += m

# Initialize the FacetGrid chart object
pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal)

# Draw the densities in a few steps
g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
g.map(plt.axhline, y=0, lw=2, clip_on=False)


# Define and use a simple function to label the plot in axes coordinates
def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .2, label, fontweight="bold", color=color,
            ha="left", va="center", transform=ax.transAxes)

# Use ``map()`` to calculate the label positions
g.map(label, "x")

# Set the subplots to overlap slightly on their vertical direction
g.fig.subplots_adjust(hspace=-.3)

# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=True, left=True)
g.fig.subplots(figsize=(12,12))  # Don't know how to change figure size for a set of overlapping Seaborn plots

我收到以下警告,然后是错误消息,然后显示 FacetedGrid 图而不更改其大小。

  self.fig.tight_layout()
C:\Anaconda3\lib\site-packages\seaborn\axisgrid.py:848: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  self.fig.tight_layout()
C:\Anaconda3\lib\site-packages\seaborn\axisgrid.py:848: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  self.fig.tight_layout()

<ipython-input-25-a661dbef6e83> in <module>
     43 g.set(yticks=[])
     44 g.despine(bottom=True, left=True)
---> 45 g.fig.subplots(size=(12,12))  # Don't know how to change figure size for a set of overlapping Seaborn plots

TypeError: subplots() got an unexpected keyword argument 'size'

#############

在集成所有 cmets 后,以下是没有警告或错误的良好、紧凑绘图的源代码:

`# -*- coding: utf-8 -*-
""" Created on Mon Jun 24 12:21:40 2019 @author: rlysak01 
FacetGrid Plot Showing Overlapping Distributions (Densities) Offset by ('ridge plot')
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})

# Create some random distribution data and labels, and store them in a dataframe
rs = np.random.RandomState(1979)
x = rs.randn(500)
g = np.tile(list("ABCDEFGHIJ"), 50)
df = pd.DataFrame(dict(x=x, g=g))
m = df.g.map(ord)
df["x"] += m

# Initialize the FacetGrid chart object
pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
# g = sns.FacetGrid(df, row="g", hue="g", aspect=6, height=1.0, palette=pal)
g = sns.FacetGrid(df, row="g", hue="g", palette=pal)

''' Alternatively set figsize using the following 2 parameters.'''
g.fig.set_figheight(5.5)
g.fig.set_figwidth(7)
# or use plt.gcf().set_size_inches(12, 12)

# Draw the densities in a few steps
g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
g.map(plt.axhline, y=0, lw=2, clip_on=False)

# Define and use a simple function to label the plot in axes coordinates
# Values x,y in ax.text(x,y, ...) controls the x,y offset from the x axis.
def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .2, label, fontweight="bold", color=color,
            ha="left", va="center", transform=ax.transAxes)

# Use ``map()`` to calculate the label positions
g.map(label, "x")

# Set the subplots to overlap slightly on their vertical direction
g.fig.subplots_adjust(hspace=-0.5)

# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=True, left=True)
`

【问题讨论】:

  • 感谢您正确接受答案的指导。

标签: python-3.x matplotlib seaborn


【解决方案1】:

我找到了一个解决方案,您可以将高度和宽度分别设置为

g.fig.set_figheight(12)
g.fig.set_figwidth(12)

或者,您可以尝试将当前图形的大小设置为

g.despine(bottom=True, left=True)
plt.gcf().set_size_inches(12, 12)

使用上述行输出 (5,5) 尺寸的示例

【讨论】:

  • 感谢您的回答。顶级解决方案效果很好。以英寸为单位工作时,限制为 5.5" x 1.5",以免产生错误。对于 2" 大小的绘图,实际最小尺寸的绘图约为 6",这使得绘图可用。
  • 我做了更多的测试。 5.5" 垂直设置是可用的。我测试了不同的宽度设置,它在从 ~ 1 英寸宽(完全不切实际)到 22+ 英寸的屏幕宽度限制的任何地方都显示没有警告。
  • 我做了更多测试以控制图形可用性的最佳设置是:g.fig.set_figheight(5.5) g.fig.set_figwidth(6) 在 sns.FacetGrid() 中消除 aspect=6 和 height=1.0,使其看起来像这样:g = sns .FacetGrid(df, row="g", hue="g", palette=pal)` 因为它们是多余的并且无论如何都会被覆盖。
【解决方案2】:

除了Sheldore 的回答,FacetGrid 的尺寸由以下控制:

高度:标量,可选

Height (in inches) of each facet. See also: aspect.

方面:标量,可选

Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches.

因此,如果您想要最终的图形大小为 12x12 英寸,并且您有 10 个子图,则需要 height = 12/10 = 1.2width = aspect * height,或 aspect = width/height = 12/1.2 = 10

因此,您需要使用以下方法创建 FacetGrid:

g = sns.FacetGrid(df, row="g", hue="g", aspect=10, height=1.2, palette=pal)

【讨论】:

  • 这比仅仅改变高度和宽度更好地解释了令人困惑的行为。纵横比、高度、子图之间的间距(“g.fig.subplots_adjust(hspace=-1.5)”中的参数)和各个子图标签大小都相互作用以控制适当的重叠和显示。增加 hspace 参数(在代码行中:g.fig.subplots_adjust(hspace=-.5) 到大于 1,子图垂直翻转并且子图开始变得越来越小。这些参数之间存在微妙的相互作用以使图看起来正确且有用。使用 aspect=6 和 height=1.0 与 hspace = -0.5 很好。
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 2021-07-24
  • 2021-01-28
  • 2014-05-09
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 2021-01-11
相关资源
最近更新 更多