首页 > 解决方案 > 有没有一种方法可以绘制 CSV 文件中的数据,其中每列中的每 10 个数据点是同一图表中的不同线?

问题描述

假设我有一个分为两列的数据集。我想绘制一个每 10 个迭代的线图。因此,我将取前 10 个,然后是前 10 个正下方的第二个 10,作为同一图表上的另一个线图(不同颜色的线)。数据在没有标题的 CSV 文件中相互堆叠。

目前,我将其纳入整个专栏。它绘制了它们,但是对于它是哪个数据集没有区别。我想在同一张图上绘制多条线,但 CSV 文件在一列中包含所有数据集,但我需要每 10 个绘制一次。

编辑 下面我添加了数据我希望第一列是 x 轴,第二列是 y。

Sample Data:
0   8.2
1   9.1
2   2.2
3   3.3
4   9.8
5   6.3
6   4.8
7   8.6
8   3.9
9   2.1
0   9.34
1   10.2
2   7.22
3   6.98
4   1.34
5   2.56
6   6.78
7   4.56
8   3.3
9   9.4

标签: pythonpandasloopscsvmatplotlib

解决方案


好的,试试这个:

# this is the toy data
df = pd.DataFrame({0:list(range(10))*2,
                1:np.random.uniform(9,11,20)})

# set up axes for plots
fig, ax = plt.subplots(1,1)

# the groupby argument groups every 10 rows together
# then pass it to the `lambda` function,
# which plots each chunk to the given plt axis
df.groupby(df.reset_index().index//10).apply(lambda x: ax.plot(x[0], x[1]) )
plt.show()

在此处输入图像描述

选项 2:

我发现sns这是一个更好的工具:

fig, ax = plt.subplots(1,1, figsize=(10,6))
sns.lineplot(x=df[0], 
             y=df[1], 
             hue=df.reset_index().index//10, 
             data=df,
             palette='Set1')
plt.show()

输出:

在此处输入图像描述


推荐阅读