如何向seaborn FacetGrid的每个子图添加个别垂直线。

12

我想在每个子图中添加一条垂直线,以标记每个产品的单独启动日期。每条垂直线都应显示日期。但我太新手了,无法弄清楚这个问题。我尝试使用 .axvline 的示例:

产品分面网格

这是代码:

g = sns.FacetGrid(df2, col='Product', hue='Vendor', col_wrap=4, height=3.5)
g = g.map(plt.plot, 'Date', 'Volumes')
g = g.map(plt.fill_between, 'Date', 'Volumes', alpha=0.2).set_titles("{col_name} Product")
g = g.set_titles("{col_name}")
g = g.set(xticks=[0, 12, 23])
g = g.set(xlabel='')

plt.axvline(x='Apr 19', color='r', linestyle=':')

我找到了以下方法,但是我无法理解它的实际用途或将其应用于自己的目的:

在可视化时间序列时标记特定日期

根据事件出现情况向 Seaborn Facet Grid 图中添加垂直线

我创建了两个列表,分别包含产品名称和相应的发布日期:

product_names = ['Product A', 'Product B','Product C', 'Product D','Product E', 'Product F',
                 'Product G', 'Product H','Product I', 'Product J',]

launch_dates = ['2019-02-01', '2019-09-01', '2019-12-01', '2019-12-01',
                '2020-02-01', '2020-05-01', '2020-07-01', '2020-07-01',
                '2020-08-01', '2020-07-15']

launch_dates = [datetime.strptime(d, "%Y-%m-%d") for d in launch_dates]

那么,我应该如何迭代所有的因素以添加所提到的垂直线?


这个回答解决了你的问题吗?如何在给定的图中画出垂直线 - Trenton McKinney
1个回答

12
你可以使用 g.axes.flat 访问 FacetGridaxes 对象,并在每个对象上添加一条直线,可以在特定的x位置上添加,也可以从每个个体面板的列表中收集添加:

您可以使用 g.axes.flat 访问 FacetGrid 的 axes 对象,并向每个对象添加一条线,可以在给定的x位置上添加,也可以从每个单独面板的列表中收集添加:

<code><code><code>import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

g = sns.FacetGrid(tips, col="time", row="sex")
g.map_dataframe(sns.histplot, x="total_bill", binwidth=2)
g.set_axis_labels("Total bill", "Count")

line_position = [14, 23, 11, 39]

for ax, pos in zip(g.axes.flat, line_position):
    ax.axvline(x=pos, color='r', linestyle=':')

plt.tight_layout()
plt.show()
</code></code></code>

样例输出:

输入图像描述


现在,如何将垂直线添加到图例中? - undefined
看,例如这里 - undefined
我会检查一下,但我不认为是这样的。显然,seaborn在一个轴上设置了分面图的图例。这样就会将图例放在没有分面图例对象的图上。 - undefined

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