gpt4 book ai didi

python - 如何使用多部分seaborn图迭代填充matplotlib gridspec?

转载 作者:行者123 更新时间:2023-12-01 02:24:31 26 4
gpt4 key购买 nike

我正在处理的一些最小代码。有些参数可能看起来多余,但我没有费心删除所有参数。

import matplotlib
import matplotlib.gridspec as gridspec
matplotlib.use("macosx")
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

def plot_overlaid_2d_hist(data,
plot_axis_x,
plot_axis_y,
plot_axis_x_lab,
plot_axis_y_lab,
group_by = "group_name"):

# don't mind this for now
df = data

# Figure aspect
w, h = plt.figaspect(1)
fig = plt.figure(figsize = (w, h))

# Count the number of groups to make plots for
n_groups = len(df.groupby(group_by))
gs = gridspec.GridSpec(nrows = n_groups, ncols = 1)
subplot_id = 0

# Reshape data to make it work
for name, group in df.groupby(group_by, sort = False):

# Initialize subplot
fig.add_subplot(gs[subplot_id, 0])

# Check if we get subplots with pyplot
if subplot_id == 0:
col = "red"
else:
col = "blue"

plt.plot(x, y, color = col)


# instantiate JointGrid
# g = sns.JointGrid(group[plot_axis_x],
# group[plot_axis_y],
# data = group,
# space = 0,
# xlim = (0, 1.2),
# ylim = (0, 1))
#
# # Fix labels
# g = g.set_axis_labels(xlabel = str(plot_axis_x_lab),
# ylabel = str(plot_axis_y_lab))
#
# # center scatter plot on top
# g = g.plot_joint(plt.scatter,
# s = 0.5,
# alpha = 1,
# linewidth = 1)
#
# # marginals plot
# g = g.plot_marginals(sns.distplot,
# kde = True,
# kde_kws = dict(linewidth = 2,
# alpha = 1,
# bw = "Scott"),
# hist_kws = dict(alpha = 1))


# Next plot in row +1
subplot_id += 1

# Output
plt.tight_layout() # Attempts to fix alignment of subplot layout and axis titles

plt.show()

# quick data to check if the plots end up where they should
x = [0.5, 0.5, 0.4, 0.4]
y = [0.6, 0.4, 0.3, 0.4]
grp = ["a", "a", "b", "b"]


df = pd.DataFrame({"x":x,
"y":y,
"grp": grp})

plot_overlaid_2d_hist(data = df,
group_by = "grp",
plot_axis_x_lab = "x",
plot_axis_y_lab = "x",
plot_axis_y = "x",
plot_axis_x = "x")

在所有seaborn图(g)注释掉的情况下运行代码表明它对于 native pyplot工作正常,但是当我添加多部分seaborn图时,它们显示在单独的图中。我想要的是让每个 2D-histogram-with-marginals-and-scatter 填充自己的 gridspec 行/列。

最佳答案

看到这个问题已经被问过here我将此答案移至较旧的问题。我想在这里删除它,但无法这样做,因为它已经被接受

正如在多个地方所指出的( this question ,以及 this issue ),一些 seaborn 命令会自动创建自己的图形。这是硬编码到seaborn代码中的,因此目前无法在现有的图形中生成这样的图。这些是 PairGridFacetGridJointGridpairplotjointplot lmplot

有一个seaborn fork available这将允许向相应的类提供子图网格,以便在预先存在的图形中创建图。要使用它,您需要将axisgrid.py从fork复制到seaborn文件夹。请注意,当前仅限与 matplotlib 2.1(也可能是 2.0)一起使用。

另一种方法是创建一个seaborn图形并将轴复制到另一个图形。其原理见this answer并且可以扩展到 Searborn 地 block 。实现比我最初预期的要复杂一些。下面是一个 SeabornFig2Grid 类,可以使用 Seaborn 网格实例(上述任何命令的返回)、一个 matplotlib 图和一个 subplot_spec 来调用,它是一个gridspec 网格的位置。

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
import numpy as np

class SeabornFig2Grid():

def __init__(self, seaborngrid, fig, subplot_spec):
self.fig = fig
self.sg = seaborngrid
self.subplot = subplot_spec
if isinstance(self.sg, sns.axisgrid.FacetGrid) or \
isinstance(self.sg, sns.axisgrid.PairGrid):
self._movegrid()
elif isinstance(self.sg, sns.axisgrid.JointGrid):
self._movejointgrid()
self._finalize()

def _movegrid(self):
""" Move PairGrid or Facetgrid """
self._resize()
n = self.sg.axes.shape[0]
m = self.sg.axes.shape[1]
self.subgrid = gridspec.GridSpecFromSubplotSpec(n,m, subplot_spec=self.subplot)
for i in range(n):
for j in range(m):
self._moveaxes(self.sg.axes[i,j], self.subgrid[i,j])

def _movejointgrid(self):
""" Move Jointgrid """
h= self.sg.ax_joint.get_position().height
h2= self.sg.ax_marg_x.get_position().height
r = int(np.round(h/h2))
self._resize()
self.subgrid = gridspec.GridSpecFromSubplotSpec(r+1,r+1, subplot_spec=self.subplot)

self._moveaxes(self.sg.ax_joint, self.subgrid[1:, :-1])
self._moveaxes(self.sg.ax_marg_x, self.subgrid[0, :-1])
self._moveaxes(self.sg.ax_marg_y, self.subgrid[1:, -1])

def _moveaxes(self, ax, gs):
#https://stackoverflow.com/a/46906599/4124317
ax.remove()
ax.figure=self.fig
self.fig.axes.append(ax)
self.fig.add_axes(ax)
ax._subplotspec = gs
ax.set_position(gs.get_position(self.fig))
ax.set_subplotspec(gs)

def _finalize(self):
plt.close(self.sg.fig)
self.fig.canvas.mpl_connect("resize_event", self._resize)
self.fig.canvas.draw()

def _resize(self, evt=None):
self.sg.fig.set_size_inches(self.fig.get_size_inches())

这个类的用法如下:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns; sns.set()
import SeabornFig2Grid as sfg


iris = sns.load_dataset("iris")
tips = sns.load_dataset("tips")

# An lmplot
g0 = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips,
palette=dict(Yes="g", No="m"))
# A PairGrid
g1 = sns.PairGrid(iris, hue="species")
g1.map(plt.scatter, s=5)
# A FacetGrid
g2 = sns.FacetGrid(tips, col="time", hue="smoker")
g2.map(plt.scatter, "total_bill", "tip", edgecolor="w")
# A JointGrid
g3 = sns.jointplot("sepal_width", "petal_length", data=iris,
kind="kde", space=0, color="g")


fig = plt.figure(figsize=(13,8))
gs = gridspec.GridSpec(2, 2)

mg0 = sfg.SeabornFig2Grid(g0, fig, gs[0])
mg1 = sfg.SeabornFig2Grid(g1, fig, gs[1])
mg2 = sfg.SeabornFig2Grid(g2, fig, gs[3])
mg3 = sfg.SeabornFig2Grid(g3, fig, gs[2])

gs.tight_layout(fig)
#gs.update(top=0.7)

plt.show()

enter image description here

请注意,复制轴可能存在一些缺点,并且上述内容尚未经过彻底测试。

关于python - 如何使用多部分seaborn图迭代填充matplotlib gridspec?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com