【问题标题】:How to add individual vlines to every subplot of seaborn FacetGrid如何将单个 vlines 添加到 seaborn FacetGrid 的每个子图
【发布时间】:2021-05-15 04:42:30
【问题描述】:

我想在每个子图上添加一条垂直线来标记每个产品的单独发布日期。每条垂直线都应显示日期。但我太初学者了,无法弄清楚。我以.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=':')

我找到了以下方法,但我无法真正理解它,或者将其应用于我自己的目的:

Marking specific dates when visualizing a time series

Add vertical lines to Seaborn Facet Grid plots based on the occurrence of an event

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

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]

那么,如何遍历所有方面以添加提到的垂直线?

【问题讨论】:

    标签: python seaborn facet-grid


    【解决方案1】:

    您可以使用g.axes.flat 访问FacetGridaxes 对象,并在给定的x 位置或从每个单独方面的列表中为每个对象添加一行:

    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()
    

    样本输出:

    【讨论】:

    • 效果很好。非常感谢您对此的支持。
    • 嗨,如果沿着同一行绘制男性和女性(2 个直方图:1 个用于午餐,1 个用于晚餐)?我的 zip(g.axes.flat, line_position, colors) 解决方案不起作用。谢谢。
    猜你喜欢
    • 2022-10-12
    • 2022-01-12
    • 2018-12-09
    • 2015-11-22
    • 1970-01-01
    • 2017-05-21
    • 2015-08-30
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多