将线条图添加到Facetgrid图

问题描述

我使用Seaborn绘制了一个简单的RelPlot对象,它为我返回了一个Facetgrid对象。 我使用的代码如下:

import seaborn as sns

palette = sns.color_palette("rocket_r")

g1 = sns.relplot(
    data=df,x="number_of_weeks",y="avg_streams",hue="state",col="state",kind="line",palette=palette,height=5,aspect=1,facet_kws=dict(sharex=False),col_wrap=3,)

显示以下情节:

Plot

我正在使用的数据框具有以下结构:

   avg_streams  date    year number_of_weeks state
4   0.104011    31-01   2020    4   it
5   1.211951    07-02   2020    5   it
6   0.559374    14-02   2020    6   it
7   0.304257    21-02   2020    7   it
8   0.199218    28-02   2020    8   it
... ... ... ... ... ...
175 -0.938890   26-06   2020    25  br
176 -0.483821   03-07   2020    26  br
177 -0.083704   10-07   2020    27  br
178 0.165312    17-07   2020    28  br
179 0.218601    24-07   2020    29  br

我想将其他线图添加到单个子图中。我的最终目标是绘制每个子图中的所有线,但突出显示每个不同子图的不同状态。

因此,我想为Facetgrid中的每个不同子图获取类似的信息:

enter image description here

这是我为上一个情节编写的代码:

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

palette = {c:'red' if c=='it' else 'grey' for c in df.state.unique()}

fig,ax = plt.subplots(figsize=(15,7))    
plot=sns.lineplot(ax=ax,data=df,palette=palette)

lines = ax.get_lines()
lines[0].set_linewidth(5)

plot.set(title='Streams trend')

但是我不知道如何“合并”这两个情节。我如何实现我的目标?

编辑:我试图“手动”添加图,选择Facetgrid的单轴。我遵循了这个问题:Add lineplot to subplot,我能够添加一条简单的线。

这是我的尝试,我试图在已经存在的绘图中添加一条简单的线:

palette = sns.color_palette("rocket_r")

g1 = sns.relplot(
    data=df,)
axes = g1.fig.axes
print(axes)

axes[0].plot([20,30],[40,50],'k-')

enter image description here

解决方法

我找到了一个解决方案,代码如下:

import seaborn as sns

palette = sns.color_palette("tab10",6)

g1 = sns.relplot(
    data=df,x="number_of_weeks",y="avg_streams",hue="state",col="state",kind="line",palette=palette,height=5,aspect=1,facet_kws=dict(sharex=False),col_wrap=3,linewidth=5,zorder= 5
)
axes = g1.fig.axes
states = df.state.unique()

for index,state in enumerate (states,start=0):
    df_temp = df.loc[df['state'] != state]
    palette1 = {c:'grey' for c in df_temp.state.unique()}
    sns.lineplot(ax=axes[index],data=df_temp,palette=palette1)
    axes[index].get_legend().remove()
    axes[index].set_xlabel('')

    

这是结果: enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...