python用斜率绘制两个时间点

2024-10-01 00:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把几个图绘制成FacetGrid,每个图包括两个时间点。此外,我还想计算并显示直线的坡度:

ID     TimePoint1    TimePoint2
================================
A      500           20000
B      200           1000
C      3000          50000

大概是这样的: enter image description here

我尝试了这个代码示例,但图中没有显示任何内容:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_table("test.csv", sep=",")
g = sns.FacetGrid(data, col="ID", col_wrap=4, height=2, ylim=(0, 10))
g.map(sns.pointplot, "TimePoint1", "TimePoint2", color=".3", ci=None)

我如何通过seaborn实现这一点


Tags: importiddataas时间绘制colseaborn
1条回答
网友
1楼 · 发布于 2024-10-01 00:18:31

这里使用TimePoint1作为x,TimePoint2作为y。要实现您想要的,您首先需要重塑数据。假设data输入数据:

import pandas as pd
import matplotlib.pyplot as plt
data_long = (data.rename(columns=lambda x: int(x[-1]) if x.startswith('TimePoint') else x)
                 .melt(id_vars=['ID'], var_name='TimePoint')
             )
g = sns.FacetGrid(data_long, col="ID", col_wrap=4, height=2,) # ylim=(0, 10))
g.map(sns.pointplot, "TimePoint", "value", color=".3", ci=None)

输出:

seaborn pointplot

NB。我删除了无效的ylim

数据长度:

  ID TimePoint  value
0  A         1    500
1  B         1    200
2  C         1   3000
3  A         2  20000
4  B         2   1000
5  C         2  50000

您还可以方便地使用^{},它是FacetGrid的包装器:

sns.catplot(data=df_long, x='TimePoint', y='value', col='ID',
            col_wrap=4, height=2, color=".3", ci=None, kind='point'
           )

相关问题 更多 >