Seaborn设置figsize=(x,y)时出现错误和关于tight_layout的警告:“tight_layout无法使轴高度足够小以容纳所有轴装饰”。

3
我有一个包含10个略有重叠的图形的Seaborn FacetGrid图表。 我想改变整个图形的大小。 当我在下面的代码中使用g.fig.subplots(figsize =(12,12))时,我会收到错误消息“TypeError:subplots()得到了一个意外的关键字参数'size'”。
此外,我会收到一个警告:“UserWarning:未应用紧凑布局。tight_layout无法使轴高度足够小以容纳所有轴装饰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图表显示而未改变其大小。

警告信息:Original Answer

错误信息:请检查您的代码并确保正确使用了大小参数。

  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'

将所有评论整合后,以下是一个优秀的、紧凑的情节源代码,没有警告或错误:

最初的回答:

`# -*- 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)
`

感谢对正确接受答案的指导。 - undefined
2个回答

8
我找到了一个解决方案,您可以分别设置高度和宽度,如下所示:
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"的限制。实际上,最小的可用绘图尺寸大约是6英寸,对于2英寸大小的绘图来说,这使得绘图可用。 - undefined
我进行了一些额外的测试。5.5英寸的垂直设置是可用的。我测试了不同的宽度设置,它可以在从大约1英寸宽(完全不实用)到22英寸以上的屏幕宽度限制下显示,而没有任何警告。 - undefined
我进行了一些测试,发现控制图形可用性的最佳设置是: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),因为它们是多余的,并且会被覆盖。 - undefined

2

除了Sheldore的答案之外,FacetGrid的维度是由以下控制的:

height : scalar, optional

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

aspect : scalar, optional

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搭配效果良好。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接