gpt4 book ai didi

python - 将线图添加到 Facetgrid 图中

转载 作者:行者123 更新时间:2023-12-03 08:35:30 26 4
gpt4 key购买 nike

我使用 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,x="number_of_weeks", y="avg_streams", hue="state", 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,
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,
)
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],x="number_of_weeks", y="avg_streams", hue="state", data=df_temp, palette=palette1)
axes[index].get_legend().remove()
axes[index].set_xlabel('')


这就是结果: enter image description here

关于python - 将线图添加到 Facetgrid 图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63960329/

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