我的数据是这样组织的:
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
换句话说:我有多个项目的数据集,每个数据集由多个 x/y 对组成,但每个数据集都有自己不同的 x 值集。
现在我想将所有这些数据绘制在同一个图上,如下所示: (抱歉,今晚无法上传图片,但所有数据集应绘制在同一 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()
这给出了