Pandas Dataframe将行绘制为x值,将列标题绘制为y值

时间:2017-04-25 09:25:43

标签: python pandas matplotlib plot

我有一个Pandas DataFrame,其中包含不同时间(行)和特定垂直位置(列名称)的位移。目标是绘制给定时间(系列)的垂直位置(y轴)的位移(x轴)。

根据下一个例子(时间= 0,1,2,3,4和垂直位置= 0.5,1.5,2.5,3.5),如何绘制位移0和3的位移?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(88)
df = pd.DataFrame({
    'time': np.arange(0, 5, 1),
    '0.5': np.random.uniform(-1, 1, size = 5),
    '1.5': np.random.uniform(-2, 2, size = 5),
    '2.5': np.random.uniform(-3, 3, size = 5),
    '3.5': np.random.uniform(-4, 4, size = 5),
    })
df = df.set_index('time')

1 个答案:

答案 0 :(得分:2)

您可以将数据框过滤为仅包含所需的行。通过使用位置索引

filtered = df.iloc[[0,3],:]

或使用数据框的实际索引,

filtered = df.iloc[(df.index == 3) | (df.index == 0),:]

然后您可以绘制如下的散点图:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(88)
df = pd.DataFrame({
    'time': np.arange(0, 5, 1),
    '0.5': np.random.uniform(-1, 1, size = 5),
    '1.5': np.random.uniform(-2, 2, size = 5),
    '2.5': np.random.uniform(-3, 3, size = 5),
    '3.5': np.random.uniform(-4, 4, size = 5),
    })
df = df.set_index('time')


filtered_df = df.iloc[[0,3],:]
#filtered_df = df.iloc[(df.index == 3) | (df.index == 0),:]

loc = list(map(float, df.columns))

fig, ax = plt.subplots()
for row in filtered_df.iterrows():
    ax.scatter(row[1], loc, label=row[1].name)

plt.legend()    
plt.show()

enter image description here