不同x轴坐标的多个数据集的线图

问题描述 投票:0回答:2

我的数据是这样组织的:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl

df = pd.DataFrame({(1,'x'):[0,1,2],(1,'y'):[10,11,12],
                   (2,'x'):[1,2,3],(2,'y'):[11.5,11.8,13.2]})
df

   1      2      
   x   y  x     y
0  0  10  1  11.5
1  1  11  2  11.8
2  2  12  3  13.2

换句话说:我有多个项目的数据集,每个数据集由多个 x/y 对组成,但每个数据集都有自己不同的 x 值集。

现在,我想将所有数据绘制在同一个图上,如下所示:

我可以用循环轻松完成,如下所示:

fig1,ax = plt.subplots()
for item in range(1,3):
    df.xs(item,axis=1,level=0).plot(ax=ax,kind='line',x='x',y='y',
                                    style='o-',label=str(item))

但我想知道是否有一种方法可以在不使用循环的情况下获得相同的绘图。

python pandas matplotlib plot
2个回答
0
投票

由于您的数据框不是直接适合绘图的格式,我的建议是在绘图之前将其融合为长格式:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
df = pd.DataFrame({(1,'x'):[0,1,2],(1,'y'):[10,11,12],(2,'x'):[1,2,3],(2,'y'):[11.5,11.8,13.2]})

reformatted_data = []

for (item, coord), values in df.items():
    for index, value in enumerate(values):
        if len(reformatted_data) <= index:
            reformatted_data.append({'Item': item})
        if 'X' not in reformatted_data[index] or item == reformatted_data[index]['Item']:
            reformatted_data[index][coord] = value
            reformatted_data[index]['Item'] = item  
df_corrected = pd.DataFrame(reformatted_data)

fig, ax = plt.subplots()
for item in df_corrected['Item'].unique():
    item_data = df_corrected[df_corrected['Item'] == item]
    ax.plot(item_data['x'], item_data['y'], marker='o', linestyle='-', label=f'Item {item}')

ax.legend()
plt.show()

这给出了


0
投票

在应用

df
 之前转换您的 
df.plot
:x 轴值的索引和 y 轴值的单独列。这是一种方法:

out = (
    df.stack(0)
    .droplevel(0)
    .set_index('x', append=True)
    .unstack(0)
    .droplevel(0, axis=1)
)

out

      1     2
x            
0  10.0   NaN
1  11.0  11.5
2  12.0  11.8
3   NaN  13.2

我们可以轻松绘制:

out.plot(kind='line', style='o-')
plt.show()

剧情

© www.soinside.com 2019 - 2024. All rights reserved.