如何在一个窗口上绘制多个 FacetGrid?

2023-12-06

在下面的代码中,我可以通过传递在一个窗口中放置两个简单的seaborn图ax=ax[i]每个论据都不起作用FacetGrid()。类似问题已被问过here,想知道是否有人知道如何做到这一点。谢谢!

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

df = sns.load_dataset('tips')

########################
# Works :)
########################
fig,ax = plt.subplots(nrows=2)
sns.regplot(x='total_bill', y='tip', data=df, ax=ax[0])         # plot #1
sns.boxplot(x='day', y='total_bill', data=df, ax=ax[1])         # plot #2
plt.show()

########################
# Does not work :(
########################
fig,ax = plt.subplots(nrows=2)
g = sns.FacetGrid(df, col="time", ax=ax[0])                             # FacetGrid #1
g.map(plt.hist, "tip")

g = sns.FacetGrid(df, col="sex", hue="smoker", col_wrap=2, ax=ax[1])    # FacetGird #2
g.map(plt.scatter, "total_bill", "tip", alpha=.7)
g.axes[-1].legend() 
plt.show()


一种(诚然不是特别简洁的解决方案)是定义自己的FacetGrid类(见代码here),这需要一个fig论证,这样你就可以通过它子图. E.g.:

from itertools import product
import warnings

import numpy as np

import matplotlib.pyplot as plt
from seaborn.axisgrid import FacetGrid, Grid
from seaborn._oldcore import categorical_order
from seaborn.utils import _disable_autolayout

class FacetGridWithFigure(FacetGrid):
    def __init__(
        self, data, *,
        row=None, col=None, hue=None, col_wrap=None,
        sharex=True, sharey=True, height=3, aspect=1, palette=None,
        row_order=None, col_order=None, hue_order=None, hue_kws=None,
        dropna=False, legend_out=True, despine=True,
        margin_titles=False, xlim=None, ylim=None, subplot_kws=None,
        gridspec_kws=None, fig=None, # additional fig argument 
    ):

        # make sure to init the parent of FacetGrid
        super(FacetGrid, self).__init__()

        # Determine the hue facet layer information
        hue_var = hue
        if hue is None:
            hue_names = None
        else:
            hue_names = categorical_order(data[hue], hue_order)

        colors = self._get_palette(data, hue, hue_order, palette)

        # Set up the lists of names for the row and column facet variables
        if row is None:
            row_names = []
        else:
            row_names = categorical_order(data[row], row_order)

        if col is None:
            col_names = []
        else:
            col_names = categorical_order(data[col], col_order)

        # Additional dict of kwarg -> list of values for mapping the hue var
        hue_kws = hue_kws if hue_kws is not None else {}

        # Make a boolean mask that is True anywhere there is an NA
        # value in one of the faceting variables, but only if dropna is True
        none_na = np.zeros(len(data), bool)
        if dropna:
            row_na = none_na if row is None else data[row].isnull()
            col_na = none_na if col is None else data[col].isnull()
            hue_na = none_na if hue is None else data[hue].isnull()
            not_na = ~(row_na | col_na | hue_na)
        else:
            not_na = ~none_na

        # Compute the grid shape
        ncol = 1 if col is None else len(col_names)
        nrow = 1 if row is None else len(row_names)
        self._n_facets = ncol * nrow

        self._col_wrap = col_wrap
        if col_wrap is not None:
            if row is not None:
                err = "Cannot use `row` and `col_wrap` together."
                raise ValueError(err)
            ncol = col_wrap
            nrow = int(np.ceil(len(col_names) / col_wrap))
        self._ncol = ncol
        self._nrow = nrow

        # Calculate the base figure size
        # This can get stretched later by a legend
        # TODO this doesn't account for axis labels
        figsize = (ncol * height * aspect, nrow * height)

        # Validate some inputs
        if col_wrap is not None:
            margin_titles = False

        # Build the subplot keyword dictionary
        subplot_kws = {} if subplot_kws is None else subplot_kws.copy()
        gridspec_kws = {} if gridspec_kws is None else gridspec_kws.copy()
        if xlim is not None:
            subplot_kws["xlim"] = xlim
        if ylim is not None:
            subplot_kws["ylim"] = ylim

        # --- Initialize the subplot grid
        # create figure if one not given as argument
        if fig is None:
            with _disable_autolayout():
                fig = plt.figure(figsize=figsize)

        if col_wrap is None:

            kwargs = dict(squeeze=False,
                          sharex=sharex, sharey=sharey,
                          subplot_kw=subplot_kws,
                          gridspec_kw=gridspec_kws)

            axes = fig.subplots(nrow, ncol, **kwargs)

            if col is None and row is None:
                axes_dict = {}
            elif col is None:
                axes_dict = dict(zip(row_names, axes.flat))
            elif row is None:
                axes_dict = dict(zip(col_names, axes.flat))
            else:
                facet_product = product(row_names, col_names)
                axes_dict = dict(zip(facet_product, axes.flat))

        else:

            # If wrapping the col variable we need to make the grid ourselves
            if gridspec_kws:
                warnings.warn("`gridspec_kws` ignored when using `col_wrap`")

            n_axes = len(col_names)
            axes = np.empty(n_axes, object)
            axes[0] = fig.add_subplot(nrow, ncol, 1, **subplot_kws)
            if sharex:
                subplot_kws["sharex"] = axes[0]
            if sharey:
                subplot_kws["sharey"] = axes[0]
            for i in range(1, n_axes):
                axes[i] = fig.add_subplot(nrow, ncol, i + 1, **subplot_kws)

            axes_dict = dict(zip(col_names, axes))

        # --- Set up the class attributes

        # Attributes that are part of the public API but accessed through
        # a  property so that Sphinx adds them to the auto class doc
        self._figure = fig
        self._axes = axes
        self._axes_dict = axes_dict
        self._legend = None

        # Public attributes that aren't explicitly documented
        # (It's not obvious that having them be public was a good idea)
        self.data = data
        self.row_names = row_names
        self.col_names = col_names
        self.hue_names = hue_names
        self.hue_kws = hue_kws

        # Next the private variables
        self._nrow = nrow
        self._row_var = row
        self._ncol = ncol
        self._col_var = col

        self._margin_titles = margin_titles
        self._margin_titles_texts = []
        self._col_wrap = col_wrap
        self._hue_var = hue_var
        self._colors = colors
        self._legend_out = legend_out
        self._legend_data = {}
        self._x_var = None
        self._y_var = None
        self._sharex = sharex
        self._sharey = sharey
        self._dropna = dropna
        self._not_na = not_na

        # --- Make the axes look good

        self.set_titles()
        self.tight_layout()

        if despine:
            self.despine()

        if sharex in [True, 'col']:
            for ax in self._not_bottom_axes:
                for label in ax.get_xticklabels():
                    label.set_visible(False)
                ax.xaxis.offsetText.set_visible(False)
                ax.xaxis.label.set_visible(False)

        if sharey in [True, 'row']:
            for ax in self._not_left_axes:
                for label in ax.get_yticklabels():
                    label.set_visible(False)
                ax.yaxis.offsetText.set_visible(False)
                ax.yaxis.label.set_visible(False)

    def tight_layout(self):
        # subfigures don't have a tight layout option
        pass

然后你可以这样做,例如:

import seaborn as sns

fig = plt.figure(figsize=(10, 4))

# create subfigs
subfigs = fig.subfigures(1, 2, wspace=0.07)

g1 = FacetGridWithFigure(tips, col="time",  row="sex", fig=subfigs[0])
g1.map(sns.scatterplot, "total_bill", "tip")

g2 = FacetGridWithFigure(tips, col="size", height=2.5, col_wrap=3, fig=subfigs[1])
g2.map(sns.histplot, "total_bill")

plt.show()

这使:

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在一个窗口上绘制多个 FacetGrid? 的相关文章

  • ResultSet 对象没有属性“find_all”

    当我抓取一个网页时 我总是遇到一个问题 AttributeError ResultSet 对象没有属性 find 您可能将项目列表视为单个项目 当您打算调用 find 时 您是否调用了 find all 谁能告诉我如何解决这个问题 我的代码
  • Keras 中的 load_model 和 Lambda 层

    如何加载具有 lambda 层的模型 这是重现行为的代码 MEAN LANDMARKS np load data mean shape 68 npy def add mean landmarks x mean landmarks np ar
  • Python XLWT调整列宽

    XLWT 的易用性给我留下了深刻的印象 但有一件事我还没有弄清楚该怎么做 我正在尝试将某些行调整为显示所有字符所需的最小宽度 换句话说 如果双击单元格之间的分隔线 excel 会做什么 我知道如何将列宽调整为预定量 但我不确定如何确定显示所
  • 将鼠标悬停在 Folium 的弹出窗口中

    用这样一个简单的例子 import folium map 1 folium Map location 45 372 121 6972 zoom start 12 tiles Stamen Terrain folium Marker 45 3
  • 尝试将行附加到按对象分组中的每个组时出现奇怪的行为

    这个问题是关于一个函数在应用于两个不同的数据帧时以意想不到的方式表现的 更准确地说 是 groupby 对象 要么是我遗漏了一些明显错误的东西 要么是 pandas 中存在错误 我编写了以下函数 将一行附加到 groupby 对象中的每个组
  • 如何在Tensorflow中读取json文件?

    我正在尝试编写一个函数 用于读取张量流中的 json 文件 json 文件具有以下结构 bounding box y 98 5 x 94 0 height 197 width 188 rotation yaw 27 970195770263
  • mypy 错误,使用 Union/Optional 重载,“重载函数签名 1 和 2 与不兼容的返回类型重叠”

    那么 让我们从一个例子开始 假设我们有几种可以组合在一起的类型 假设我们正在使用 add 来实施这一点 不幸的是 由于我们无法控制的情况 一切都必须是 可为空的 因此我们被迫使用Optional到处 from typing import O
  • OSMNX - 边缘的哪个“部分”被认为是最近的

    我正在使用 OSMNX 中的 returned edges 函数 我不清楚在进行此计算时使用边缘的哪个 部分 它是边缘的任何部分吗 是中间点吗 对于网络中的长边来说 这会产生很大的差异 这取决于您如何参数化该函数 来自nearest edg
  • python 使用曲面图和第四个变量的滑块可视化 4d 数据

    如何使用前 3 个变量和第四个变量的 3 维曲面图作为滑块来可视化 4 维数据 从 csv 文件加载 集 我写了一个非常小的示例 重点介绍了实现此目标的方法 import numpy as np import matplotlib pypl
  • 在 SQLAlchemy 中删除父级后删除子级

    我的问题如下 我有两个型号Entry and Tag通过 SQLAlchemy 中的多对多关系链接 现在我想删除所有Tag没有任何对应的Entry后Entry被删除 示例来说明我想要的内容 Entry 1带标签python java Ent
  • 如何设置 pandas DataFrame _repr_html_ 方法的默认样式?

    我有一个 pandas DataFrame 其中有一列是 url 并且我编写了以下格式化程序以将其作为链接呈现在我的笔记本中 def make clickable val target blank to open new window re
  • 如何在Python中生成0-1矩阵的所有可能组合?

    如何生成大小为 K N 的 0 1 矩阵的所有可能组合 例如 如果我取 K 2 和 N 2 我会得到以下组合 combination 1 0 0 0 0 combination 2 1 0 0 0 combination 3 0 1 0 0
  • 由 asyncio.new_event_loop 创建的事件循环挂起

    以下代码只是挂起而不打印任何内容 import asyncio async def foo loop print foo loop stop loop asyncio new event loop asyncio ensure future
  • 无法通过蓝牙读取心率服务

    我希望创建一个简单的 python 脚本 通过蓝牙从 Polar 传感器读取心率数据 我已经阅读了很多其他帖子 但找不到我能够成功执行的简单内容 我有 Polar 可穿戴设备的设备 MAC 地址 我知道我想要读取的值的服务 UUID HR
  • Numpy 相当于 if/else 不带循环

    有没有任何Pythonic方法可以删除下面代码中的for循环和if else 此代码迭代 NumPy 数组并检查条件并根据条件更改值 gt gt gt import numpy as np gt gt gt x np random rand
  • 二进制补码扩展 python?

    我想知道是否有一种方法可以像在 Python 中的 C C 中一样使用标准库 最好在位数组上 进行二进制补码符号扩展 C C Example program include
  • MySQL:进行基本搜索

    我的数据库中有一个名称表 我希望对其进行模糊搜索 例如我的数据库包含 Name ID John Smith 1 Edward Smith 2 Gabriel Gray 3 Paul Roberts 4 目前 当我通过 python 搜索数据
  • 如何在(最好是纯)Python 中解码 QR 码图像?

    TL DR 我需要一种使用 最好是纯 Python 从图像文件中解码 QR 码的方法 我有一个带有 QR 码的 jpg 文件 我想使用 Python 对其进行解码 我发现有几个库声称可以做到这一点 PyQRCode 网站在这里 http p
  • Android Systrace 没有这样的文件或目录

    这是错误消息 D Programming Tools ADT bundle sdk platform tools systrace gt python systrace py Traceback most recent call last
  • 检查Python multiprocessing.Connection 的实例吗?

    Connection对象是在打开时创建的multiprocessing Pipe 然而 尚不清楚如何检查一个对象是否是一个实例Connection 在Python3 3 4 3 3 3 2 中 检测Connection我可以 from mu

随机推荐

  • 如何在 MySQL 中设置日语模式排序规则

    我在整理方面遇到问题 我想设置排序规则以支持日语 例如 当 table firstname 包含 时 包含 的查询应返回该记录 提前致谢 这就像 大写 和 小写 对吗 mysql gt SELECT COLLATE utf8 general
  • TestNG DataProvider 从 testng.xml 配置文件读取测试数据?

    TestNG DataProvider 是否可以从 testng xml 配置文件中读取测试数据 或者由于某种原因这是不现实的 我希望能够在套件级别和类级别从该文件读取测试数据 那么 给定一个像这样的testing xml 文件 我不确定它
  • Xamarin.Forms:UWP 应用的本地化

    如果我在 UWP 设备上运行我的应用程序 我会在Output window MakePRI 警告 0xdef00522 找到语言 en de 的资源 但未找到默认语言的资源 de DE en US 更改默认语言或使用默认语言限定资源 htt
  • ng-grid 将多个项目插入单元格

    如何将多个值插入到 1 个单元格 例如将电子邮件 电话和地址插入到 1 个单元格 我需要在单元格中减少行数和更多信息 我尝试过这样的方式 angular forEach scope genData function row row getN
  • Axis2 Web 服务客户端生成 - 无需修改客户端的类型

    是否可以使用 Axis2 和 Eclipse 生成 Web 服务客户端并让它使用包中已有的 java 类型 而不是创建它自己的类型 当然 原因是如果我已经创建了类型 A 并且它创建了自己的类型 A 我不能只将类型 A 的变量分配给类型 B
  • __has_cpp_attribute 不是“类似函数”的宏?

    我正在尝试介绍 deprecated 属性到我的代码库中 然而 并不是所有我需要支持的编译器都支持这种语法 标准化之前不同编译器使用的各种方法在属性标准化提案 N2761 因此 我尝试使用此属性有条件地编译 has cpp attribut
  • Python NameError:名称未定义(与默认输入参数类型有关)

    我对我打电话的事实有疑问len myByteArray 在我声明的函数的输入参数中 我希望它成为默认参数 但 Python 似乎不喜欢它 myByteArray属于类型bytearray See 关于 bytearray 的文档在这里 我正
  • 将闭包存储在 HashMap 中

    为了学习 Rust 语言 我使用了一个旧的 C 库并尝试将其转换为 Rust 它使用了很多 C 11 闭包 我在翻译这些概念时遇到了一些困难 在 C 中我有这样的事情 library h struct Event just some dat
  • 使用 vlc 的 Python QT 应用程序不显示全屏

    我正在开发一个应用程序 其中显示多个 vlc 流 rtsp 通过双击其中一个流 该流应该全屏显示 该应用程序是使用 pyqt5 和 vlc qt 的 python 3 7 代码如下 import sys import vlc from Py
  • 从 Visual Studio 2015 中完全删除 ApplicationInsights

    我环顾四周 并没有找到一个好的答案 所以我发布这个问题 希望它可以成为其他希望完全删除 Application Insights 的人的一种 参考 我尝试的第一个显而易见的事情是从 工具和扩展 中卸载该工具 但不幸的是 这让事情变得更糟 现
  • 按价格列对表格进行排序

    这是账单清单 Service Price S1 13 CHF S2 Free S3 Free S4 40 CHF 我想使用 jQuery 或纯 JavaScript 按价格对其进行排序 不是服务器端 I tried jQuery 表排序器
  • 从浏览器中检测 USB 设备是否已插入 Javascript

    是否有基于 Javascript 的机制 我可以通过浏览器检测用户是否插入了特定的 USB 设备 出于安全原因 Web 浏览器中的 JavaScript 仅提供受限制的访问计算机资源 这是不可能将文件存储在任意文件夹中 启动应用程序或与US
  • mod_rewrite php mysql

    我对 mod rewrite 非常陌生 我一直在试图解决这个问题 但真的很困难 p 这是我的问题 我有一个页面http example com user s 81 s 81 正在从数据库中的用户 ID 读取 我想要的是一个链接 http e
  • Request.QueryString 为空时出错

    有时用户会错误地重定向到 Process ViewImages PAGEID 发生这种情况时 他们会收到以下错误 Microsoft VBScript 运行时错误 800a000d 类型不匹配 字符串 FLPM cp images cs a
  • C malloc 只为 int * 分配了 8 个字节 [重复]

    这个问题在这里已经有答案了 我正在尝试创建一个指向6元素int在函数中稍后返回它 因此为此目的我使用malloc 但它的表现似乎并不符合我的预期 这是代码 int j 0 for j lt 5 j int intBig malloc j s
  • C 编译器错误 - 初始值设定项不是常量

    我有一个用于创建新的函数GQueue GQueue newGQueue int n ele int ele size GQueue q GQueue malloc sizeof GQueue if q return NULL q gt pt
  • 直接从指针转换为模板函数?

    我试图获取指向函数模板实例的指针并将其转换为 void include
  • DataGrid 显示图像的路径而不是图像本身

    以下几行最终显示路径而不是它通向的图像 AutoGenerateColums 设置为 true 将其设置为 false 最终会出现完全空的行 System Data DataTable DataTable new System Data D
  • 如何在 React Native 上向 BottomTabNavigator 添加按钮?

    我的目标是同时拥有顶部和底部导航栏Home Dashboard and Album 但不适合SignIn 问题是 我希望将按钮放在底部而不是顶部 最后剩下的难题是如何添加Sign In按钮到底部导航栏 障碍是如果你写
  • 如何在一个窗口上绘制多个 FacetGrid?

    在下面的代码中 我可以通过传递在一个窗口中放置两个简单的seaborn图ax ax i 每个论据都不起作用FacetGrid 类似问题已被问过here 想知道是否有人知道如何做到这一点 谢谢 import pandas as pd impo