如何向现有 FacetGrid 添加子图?

问题描述 投票:0回答:1

我有 10 次测量数据,我想以特定方式绘制。 最简单的部分是这样的:

facetgrid = sns.lmplot(data=file_to_plot, col="count", col_wrap=3, x='measured_data', y='y_data')
plt.savefig(dir + f'{name}.png')
plt.close()

这将创建一个包含 4 行 3 列 10 个图的 png,最后一行只有一个图表。

FacetGrid,通过一次函数调用绘制 10 个图

首先,我希望轴标签全部在一行中

其次,我想要一个聚合所有其他图的图,并在图的“第 12”处(右下角)结束。我会这样做:

sns.regplot(data=file_to_plot, x='measured_data', y='y_data', scatter_kws={"alpha": 0})

具有 11 个图的 FacetGrid 模型

我无法掌握如何添加轴对象或类似对象到创建的现有facetgrid lmplot()。 或者我应该操纵我的数据框?

python pandas matplotlib plot seaborn
1个回答
0
投票

下面的代码使用“月”作为每个子图的变量。

  • 创建数据集的副本,将“month”替换为字符串“all”。
  • 连接原始数据集和“所有”数据集以创建面网格。
  • col_order=
    与两个额外列一起使用:一个虚拟列和一个“全部”列。
  • 之后,可以清理“虚拟”子图。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

# create a test dataset reducing the flights dataset to 10 months
flights = sns.load_dataset('flights')
months = list(flights['month'].unique())[:10]  # get first 10 months
flights = flights[flights['month'].isin(months)]

# make a copy to represent all months
flights_all = flights.copy()
flights_all['month'] = 'all'

# create the facet grid, adding a "dummy" month and an "all" month
fg = sns.lmplot(pd.concat([flights, flights_all]), x='year', y='passengers',
                col='month', col_wrap=3, col_order=months + ['dummy', 'all'],
                height=3, aspect=2)

# remove the title of the dummy subplot
fg.axes_dict['dummy'].set_title('')  # remove title of dummy subplot

# optionally remove y-axis and ticks of the dummy subplot
fg.axes_dict['dummy'].spines['left'].set_visible(False)
fg.axes_dict['dummy'].tick_params(axis='y', length=0)

# optionally change the line color in the all subplot
fg.axes_dict['all'].lines[0].set_color('crimson')

plt.show()

seaborn facetgrid with extra subplots

© www.soinside.com 2019 - 2024. All rights reserved.