2017-04-25 149 views
1

我有一個帶有不同時間(行)和特定垂直位置(列名稱)位移的Pandas DataFrame。目標是在給定時間(系列)繪製垂直位置(y軸)的位移(x軸)。根據下一個例子(時間= 0,1,2,3,4和垂直位置= 0.5,1.5,2.5,3.5),如何繪製位移0和3的位移?Pandas Dataframe將行繪製爲x值並將列標題繪製爲y值

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') 
+0

您是否在尋找散點圖(http://matplotlib.org/2.0.0/examples/shapes_and_collections/scatte r_demo.html)? – Serenity

回答

2

您可以過濾您的數據框以僅包含所需的行。無論是通過使用位置索引

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

或使用數據框的actualy指數,

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