我的数据是这样组织的:
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))
但我想知道是否有一种方法可以在不使用循环的情况下获得相同的绘图。
由于您的数据框不是直接适合绘图的格式,我的建议是在绘图之前将其融合为长格式:
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()
这给出了
在应用
df
之前转换您的
df.plot
:x 轴值的索引和 y 轴值的单独列。这是一种方法:
0
将列中的级别
df.stack
添加到索引,并删除原始索引 (df.droplevel
)。x
和
df.set_index
将列 append=True
添加到索引。0
将级别
df.unstack
返回到列,然后删除其他列级别(即 0
上的 axis=1
)。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()
剧情